Ventis
Ventis

Reputation: 488

Merging results of Android Room queries with RxJava 2

for an app I'm building using Android Room for the local persistence layer and RxJava2 for the awesomeness I've run into an issue I can't wrap my head around. Keep in mind that I'm a newbie in RxJava.

So I have 2 (or more) entities in a Room database. For example:

@Entity(tableName = "physical_tests", indices = {@Index(value = {"uuid", "day", "user_id"}, unique = true)})
public class PhysicalTest extends Task {

    @ColumnInfo(name = "exercise_duration")
    private long exerciseDuration;

    public PhysicalTest() {
        super(Type.physic, R.string.fa_icon_physical_test);
    }

    public long getExerciseDuration() {
        return exerciseDuration;
    }

    public void setExerciseDuration(long exerciseDuration) {
        this.exerciseDuration = exerciseDuration;
    }
}

And:

@Entity(tableName = "plate_controls", indices = {@Index(value = {"uuid", "day", "user_id"}, unique = true)})
public class PlateControl extends Task {

    @ColumnInfo(name = "plate_switched_on")
    private boolean mPlateSwitchedOn;

    public PlateControl() {
        super(Type.plate, R.string.fa_icon_plate_control);
    }

    public boolean isPlateSwitchedOn() {
        return mPlateSwitchedOn;
    }

    public void setPlateSwitchedOn(boolean mPlateSwitchedOn) {
        this.mPlateSwitchedOn = mPlateSwitchedOn;
    }
}

As you can see, both have a Task superclass. Now if I want to create a query that gets a list of all Tasks (PhysicalTests+PlateControls) how exactly would I do this with RxJava?

Right now I have 2 queries that return Maybe's in my Dao:

@Query("SELECT * FROM plate_controls")
Maybe<List<PlateControl>> getAllPlateControls();
@Query("SELECT * FROM physical_tests")
Maybe<List<PhysicalTest>> getAllPhysicalTests();

Simply merging these doesn't seem to work because the return types don't conform to List<Task>:

public Maybe<List<Task>> getAllTasks() {
        return Maybe.merge(mTaskDao.getAllPhysicalTests(), mTaskDao.getAllPlateControls());
}

(If this seems like overkill, I actually have several subclasses of Task that I want to merge)

Upvotes: 1

Views: 1264

Answers (1)

akarnokd
akarnokd

Reputation: 69997

You can zip up to 9 sources directly (or any number of sources if provided via an Iterable source):

public Maybe<List<Task>> getAllTasks() {
    return Maybe.zip(
         mTaskDao.getAllPhysicalTests(), 
         mTaskDao.getAllPlateControls(),
         mTaskDao.getAllX(),
         mTaskDao.getAllY(),
         mTaskDao.getAllZ(),
         (physicalTests, plateControls, xs, ys, zs) -> {
             List<Task> combined = new ArrayList<>();
             combined.addAll(physicalTests);
             combined.addAll(plateControls);
             combined.addAll(xs);
             combined.addAll(ys);
             combined.addAll(zs);
             return combined;
         }
    );

}

Upvotes: 1

Related Questions