【问题标题】:Zipping Room Flowable prevents updatesZipping Room Flowable 可防止更新
【发布时间】:2018-06-12 13:21:25
【问题描述】:

我的存储库中有一个getPlaces 方法:

override fun getPlaces(filter: FilterRequest): Flowable<List<Place>> {
    return from(placesApi.filter(filter))
            .doOnSuccess {
                placesDao.savePlaces(it)
            }
            .flatMapPublisher { it ->
                placesDao.getPlaces(it.map { it.placeId })
            }
}

此方法从 api 收集结果,然后将结果保存在数据库中并返回一个 flowable,其中包含通过 id 从数据库中检索到的位置为Flowable:

@Query("select * from Places where placeId in (:placesIds)")
fun getPlaces(placesIds: List<String>) : Flowable<List<Place>>

现在,每次我更改其中一个对象时,我都可以在整个应用程序中看到更改。

现在我想将这些结果与与当前位置的距离相结合,如下所示:

 override fun addDistanceToPlaces(req: Flowable<List<Place>>): Flowable<List<Place>> {
        return req
                .zipWith(getLastLocation().toFlowable(BackpressureStrategy.LATEST),
                        BiFunction<List<Place>, Location, List<Place>> { places, location ->
                            places.forEach {
                                var placeLocation = Location(it.placeName)
                                placeLocation.latitude = it.latitude
                                placeLocation.longitude = it.longitude

                                it.distance = location.distanceTo(placeLocation)
                            }
                            places.sortedBy {
                                it.distance
                            }
                        })
                .onErrorResumeNext { t: Throwable ->
                    req
                }

    }

这可行,但是如果我应用它,我会丢失 Room 的“更新”;更改不会通知观察者,所以我必须手动刷新。

为什么会这样? zip 不应该只是结合两个来源的排放吗?

【问题讨论】:

    标签: android rx-java2 android-room


    【解决方案1】:

    您的问题是尝试将zip 运算符用于您的用例。 Zip 通过配对输入 observable 的值来发射。它不会针对您的单个可观察对象的每次更改发出,而是当它们都发出时。查看弹珠以帮助您可视化其行为:

    http://reactivex.io/documentation/operators/zip.html

    因此,在您的情况下,Room Observable 正在发送到您的 zip 函数中,但位置 Observable 没有更新,因此您不会调用您的函数。

    我认为您正在寻找 combineLatest 运算符。这将等到 Room Observable 和 Location Observable 都售出一次,然后任何一个 observable 都可以发出,并且您的 combine 函数将被调用并将后续值发送到您的应用程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      相关资源
      最近更新 更多