Combine two LiveData objects with the same observer types

て烟熏妆下的殇ゞ 提交于 2019-12-24 11:45:51

问题


I have two Room entities, both of which derive from the same custom base class.

@Entity
public class BaseEntity {}

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

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

Both derived classes have a corresponding Dao interface.

@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();
}

The data in the two tables are diverse enough to store them separately, but my data access methods are the same. Therefore, I want to use a single Repository class to return the entries from both tables at the same time.

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

Is there a way I can combine the results from daoA.getAll() with daoB.getAll() into a single LiveData<List<BaseEntity>> object?


回答1:


I figured out a solution using 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;
    }
}


来源:https://stackoverflow.com/questions/53621531/combine-two-livedata-objects-with-the-same-observer-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!