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

Combine two LiveData objects with the same observer types

我有两个 Room 实体,它们都来自相同的自定义基础 class。

@Entity
public class BaseEntity {}

@Entity
public class EntityA extends BaseEntity {
    ...
}

@Entity
public class EntityB extends BaseEntity {
    ...
}

两个派生的classes都有相应的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();
}

两个表的数据不同,可以分开存放,但是我的数据访问方式是一样的。因此,我想使用一个存储库 class 来同时 return 来自两个表的条​​目。

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;
    }
}