Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two LiveData objects with the same observer types

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?

like image 251
mrshl Avatar asked Oct 28 '22 23:10

mrshl


1 Answers

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;
    }
}
like image 126
mrshl Avatar answered Nov 12 '22 11:11

mrshl