[英]Android and RxJava: insert into Room database a Retrofit Response
我有两个略有不同的Question类。 一个是改造呼叫结果对象,另一个是我的Android应用中的Room @Entity。
现在,我想从Interactor类(用例)类中执行以下操作:
现在我遇到的问题是使用Interactor类的RxJava创建此流。
这是所有的课程和电话。 首先是我的Interactor.class方法,它应该执行上述流:
public Single<List<Question>> getQuestionByCategoryMultiple(String parameter);
来自MyAPI.class的API CALL:
//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等混合使用,但未成功创建流。
如果您还有其他需要我解释的地方,或者需要更好地解释问题的地方,请在下面评论。
公共单> 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());
^^我不知道这是否是实现这一目标的最佳方法? 任何人都可以确认这是否是设计我要在这里做的好方法,或者是否有更好的方法或任何建议?
尽量不要使用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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.