[英]How to combine two different types LiveData with specific attribute updating?
[英]Combine two LiveData objects with the same observer types
我有两个Room实体,这两个实体均来自相同的自定义基类。
@Entity
public class BaseEntity {}
@Entity
public class EntityA extends BaseEntity {
...
}
@Entity
public class EntityB extends BaseEntity {
...
}
这两个派生类都有对应的Dao接口。
@Dao
public interface BaseDao {}
@Dao
public interface DaoA extends BaseDao {
@Query("SELECT * FROM EntityA")
public LiveData<List<EntityA>> getAll();
}
@Dao
public interface DaoB extends BaseDao {
@Query("SELECT * FROM EntityB")
public LiveData<List<EntityB>> getAll();
}
两个表中的数据足够多样化,可以分别存储它们,但是我的数据访问方法是相同的。 因此,我想使用一个Repository类来同时从两个表中返回条目。
public class Repository {
private List<BaseDao> daos;
private LiveData<List<BaseEntity>> entities;
public Repository(Application application) {
final EntityDatabase database = EntityDatabase.getInstance(application);
daos = new ArrayList();
daos.add(database.daoA());
daos.add(database.daoB());
entities = /** Combine entities from all daos into one LiveData object */;
}
public LiveData<List<BaseEntity>> getEntities() {
return entities;
}
}
有什么方法可以将daoA.getAll()和daoB.getAll()的结果合并到单个LiveData<List<BaseEntity>>
对象中?
我想出了使用MediatorLiveData的解决方案。
public class Repository {
private DaoA daoA;
private DaoB daoB;
public Repository(Application application) {
final EntityDatabase database = EntityDatabase.getInstance(application);
daos = new ArrayList();
daoA = database.daoA();
daoB = database.daoB();
}
public LiveData<List<BaseEntity>> getEntities() {
return mergeDataSources(
daoA.getAll(),
daoB.getAll());
}
private static LiveData<List<BaseEntity>> mergeDataSources(LiveData... sources) {
MediatorLiveData<List<BaseEntity>> mergedSources = new MediatorLiveData();
for (LiveData source : sources) {
merged.addSource(source, mergedSources::setValue);
}
return mergedSources;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.