合并两个具有相同观察者类型的LiveData对象

时间:2018-12-04 21:16:10

标签: android android-room android-livedata

我有两个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>>对象中?

1 个答案:

答案 0 :(得分:0)

我找到了使用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;
    }
}