我有两个稍微不同的Question类。一个是改造呼叫结果对象,另一个是我的Android应用中的Room @Entity。
现在我要从Interactor类(用例)类中执行以下操作:
现在我遇到的问题是使用Interactor类的RxJava创建此流。
这里是所有的类和电话。首先是我的Interactor.class方法,该方法应该执行上述流操作:
public Single<List<Question>> getQuestionByCategoryMultiple(String parameter);
来自MyAPI.class的API调用:
//this Question is of database.Question.
Single<List<Question>> getQuestionByCategory(String parameter);
Room数据库repository.class:
Single<Long> addGameReturnId(Game game);
Completable addQuestions(List<Question> questions);
Converter.class:
public static List<database.Question> toDatabase(List<retrofit.Question> toConvert, int id);
使用这些方法创建上述流时遇到了麻烦。我尝试将.flatmap,.zip,.doOnSuccess等混合使用,但未成功创建流。
如果您还有其他需要我解释的地方,或者需要更好地解释问题,请在下面评论。
public Single> getQuestionByCategoryMultiple(字符串参数){
return openTDBType
.getQuestionByCategory(paramters) //step 1
// step 2
// step 3
.observeOn(AndroidSchedulers.mainThread()); //step 4
}
编辑:
我尝试过这样的事情:
return openTDBType
.getQuestionByCategory(parameters)
.map(QuestionConverter::toDatabase)
.flatMap(questions -> {
int id = gameRepositoryType.addGameReturnId(new Game(parameters).blockingGet().intValue();
questions.forEach(question -> question.setqId(id));
gameRepositoryType.addQuestions(questions);
return gameRepositoryType.getAllQuestions(); })
.observeOn(AndroidSchedulers.mainThread());
^^我不知道这是否是实现这一目标的最佳方法?谁能确认这是否是设计我要在这里做的好方法,或者有更好的方法或任何建议?
答案 0 :(得分:1)
请不要使用blockingGet
,尤其是在可以避免的情况下。另外,addQuestions
根本不会被执行,因为它没有被订阅。您可以像这样将addGameReturnId
和addQuestions
都添加到链中:
return openTDBType
.getQuestionByCategory(parameters)
.map(QuestionConverter::toDatabase)
.flatMap(questions -> {
return gameRepositoryType.addGameReturnId(new Game(parameters)) // returns Single<Long>
.map(id -> {
questions.forEach(question -> question.setqId(id));
return questions;
})
}) // returns Single<List<Question>> with the GameId attached
.flatMapCompletable(questions -> gameRepositoryType.addQuestions(questions)) // returns Completable
.andThen(gameRepositoryType.getAllQuestions()) // returns Single<>
.observeOn(AndroidSchedulers.mainThread());