简体   繁体   English

RxJava - 如何使用带有两个可观察对象的 takeUntil 操作进行重复,一个可观察对象取决于其他对象

[英]RxJava - how to do repeat with takeUntil operations with two observables, one observable depending on other

I have a scenario where I need to call search api to get a list of particular item based on the search radius on map.我有一个场景,我需要调用搜索 api 以根据地图上的搜索半径获取特定项目的列表。 The requirement is to show at least five results.要求是至少显示五个结果。 In my case I have two Apis (two observables).就我而言,我有两个 Apis(两个 observables)。 First I need to call getExpandedSearchRadius() to get radius and perform second call, doSearch() with radius as parameter.首先,我需要调用getExpandedSearchRadius()来获取半径并执行第二次调用, doSearch()以半径为参数。 Suppose the doSearchApi Call returns only 2 results I need to repeat the both api calls till I get the minimum result of 5. On each repeat getExpandedSearchRadius need to call to return a new expanded radius and perform doSearch with new radius.假设doSearchApi调用仅返回 2 个结果,我需要重复两次 api 调用,直到获得最小结果 5。在每次重复时, getExpandedSearchRadius需要调用以返回新的扩展半径并使用新半径执行doSearch

Here the problem is each time the repeat() is called getExpandedSearchRadius Api is not executing, only the second call is executing with the initial radius, resulting in same searchResponse.这里的问题是每次调用repeat() getExpandedSearchRadius Api 都没有执行,只有第二次调用以初始半径执行,导致相同的 searchResponse。 below is a sample that I tried.下面是我尝试过的示例。

getExpandedSearchRadius().flatMap{ radius -> doSearch(radius)}
                      .repeat()
                      .takeUntil(searchResponse.getItems().size >=5)
                      .map(anotherClass::displayOnMap)

You can use Observable.defer(), as it acts as an Observable factory, then, when repeat operator takes effect, builder factory .defer() creates another fresh observable and will invoke getExpandedSearchRadius() also.您可以使用 Observable.defer(),因为它充当 Observable 工厂,然后,当重复操作符生效时,构建器工厂 .defer() 会创建另一个新的 observable 并且也会调用 getExpandedSearchRadius()。

See doc: ( Defer Operator)请参阅文档:(延迟运算符)

Example Code:示例代码:

Observable.defer(() -> getExpandedSearchRadius())
        .flatMap{ radius -> doSearch(radius)}
                  .repeat()
                  .takeUntil(searchResponse.getItems().size >=5)
                  .map(anotherClass::displayOnMap)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM