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

问题描述 投票:1回答:1

对于我正在使用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子类)

android rx-java2 android-room
1个回答
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;
         }
    );

}

© www.soinside.com 2019 - 2024. All rights reserved.