[英]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.