Android和RxJava:将翻新响应插入Room数据库

时间:2019-04-08 15:53:08

标签: android rx-java rx-java2

我有两个稍微不同的Question类。一个是改造呼叫结果对象,另一个是我的Android应用中的Room @Entity。

现在我要从Interactor类(用例)类中执行以下操作:

  1. 调用API和结果(列出问题所在 改造响应类)
  2. 成功后,在Room数据库中创建一个新的Game对象。此操作有很长的时间(自动生成的@Entity ID)作为返回值 类型。
  3. 对于来自改造响应(来自(1))的每个Question,问题->转换器,将从Retrofit.Question转换为 数据库。问题转换器方法采用2个参数, retrofit.Question对象和在步骤(2)中返回的ID。 转换后,添加到数据库。
  4. 在AndroidSchedulers.mainthread上进行观察。 (subscribeOn从存储库中调用)

现在我遇到的问题是使用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());

^^我不知道这是否是实现这一目标的最佳方法?谁能确认这是否是设计我要在这里做的好方法,或者有更好的方法或任何建议?

1 个答案:

答案 0 :(得分:1)

请不要使用blockingGet,尤其是在可以避免的情况下。另外,addQuestions根本不会被执行,因为它没有被订阅。您可以像这样将addGameReturnIdaddQuestions都添加到链中:

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