【问题标题】:RxJava, Room: Best way to update all the rows of Db using rxjava chain callsRxJava,Room:使用 rxjava 链调用更新所有 Db 行的最佳方法
【发布时间】:2018-09-23 23:29:54
【问题描述】:

我正在使用 rxjava 和 Room 来尝试更新 db 中的行列表。 陷入事件不断触发的循环中

@Query("SELECT * FROM movies")
Flowable<List<Movie>> getMovies();

@Update
int updateMovie(Movie movie);

UpdateClass - 帮助类正在像这样更新 Db

// Trying to get all existing movies and update one value in all of them.

@WorkerThread
Flowable<Integer> updateMovies(Helper help) {
    return movieDao.getMovies().flatMapIterable(movies -> movies)
        .flatMap(movie -> {
            LogUtils.debug("movieusecase", "movieid" + movie.getMovieId());
            movie.updateRating(help.getUpdatedVal(movie));
            return Flowable.just(movie);
        }).map(movie -> {
           return movieDao.updateMovie(movie);
        });
}

一旦我加入updateMovie 调用,我就会陷入无限循环,重复事件不断来自房间数据库。

Presenter Class - 调用更新类来更新数据库中的内容。在活动onCreate中触发

updateClass.updateMovies()
    .observable.subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(movie -> {
        // update stuff
    }, throwable -> {
        LogUtils.error(TAG, throwable.getMessage());
    });

在此先感谢您的任何帮助。

【问题讨论】:

    标签: java rx-java rx-java2 android-room


    【解决方案1】:

    听起来像是Single 而不是Flowable 的工作。

    不同之处在于Single 只会在数据库中的当前电影列表触发一次,它不会像Flowable 那样不断发出变化。

    Single<List<Movie>> getMovies();
    

    或者如果您出于某种原因希望您的方法返回Flowable,您也可以使用Flowable.firstOrError(),它将您的Flowable 转换为带有costSingle

    @WorkerThread
    Flowable<Integer> updateMovies(Helper help) {
        return movieDao.getMovies()
            .firstOrError()
            .flatMapIterable(movies -> movies)
            .flatMap(movie -> { ... })
            .map(movie -> { ... });
    }
    

    但为了清楚起见,我更喜欢第一个选项。

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多