![](/img/trans.png)
[英]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.