合并两个具有相同观察者类型的LiveData对象 [英] Combine two LiveData objects with the same observer types

查看:1021
本文介绍了合并两个具有相同观察者类型的LiveData对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个Room实体,它们都是从相同的自定义基类派生的.

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 {
    ...
}

两个派生类都有对应的Dao接口.

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

两个表中的数据足够多样化,可以分别存储,但是我的数据访问方法是相同的.因此,我想使用一个Repository类同时从两个表中返回条目.

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

有没有办法将daoA.getAll()和daoB.getAll()的结果合并到单个LiveData<List<BaseEntity>>对象中?

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

推荐答案

我找到了使用MediatorLiveData的解决方案.

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

这篇关于合并两个具有相同观察者类型的LiveData对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆