将Android Room查询的结果与RxJava 2合并

时间:2018-02-28 13:15:16

标签: android rx-java2 android-room

对于我正在使用Android Room为本地持久层构建的应用程序和RxJava2为我所遇到的令人敬畏的问题我无法解决这个问题。 请记住,我是RxJava的新手。

所以我在Room数据库中有2个(或更多)实体。例如:

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

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

如您所见,两者都有一个Task超类。现在,如果我想创建一个获取所有任务列表(PhysicalTests + PlateControls)的查询,我将如何使用RxJava执行此操作?

现在我有2个查询在我的Dao中返回Maybe's:

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

简单地合并这些似乎不起作用,因为返回类型不符合List<Task>

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

(如果这看起来有点矫枉过正,我实际上有几个我要合并的Task子类)

1 个答案:

答案 0 :(得分:1)

您可以直接zip最多9个来源(或通过Iterable来源提供的任意数量的来源):

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

}