How to use Reactor (Spring WebClient) to do a repeat call?

自闭症网瘾萝莉.ら 提交于 2019-12-08 07:53:30

问题


I am using Reactor (Spring5 WebClient) as my reactive programming API. I have 2 REST endpoint to call. The result of the first one will be the parameter to the second one. For the second API, it will return a result with "hasMore" value. If this value is true, I should change the pagination parameters and call the second API again. The demo code is the following:

 client.getApi1()
        .map(r -> r.getResult())
        .flatMap(p -> client.getApi2(p, 2(page size), 1(page start)))
        .subscribe(r -> System.out.println(r.isHasmore()));

How to repeat calling the second API (getApi2) until "hasMore" is false.

Besides, I need to change the parameters page size and page start


回答1:


Try this code:

 AtomicInteger pageCounter = new AtomicInteger(0);
 client.getApi1()
    .map(r -> r.getResult())
    .flatMap(p -> client.getApi2(p, 2(page size), pageCounter.incrementAndGet()))
    .repeat()            
    .takeWhile(r -> r.isHasmore())
    .subscribe(r -> System.out.println(r.isHasmore()));

repeat() calls getApi2 infinitely. takeWhile(continuePredicate) relays values while a continuePredicate (r.isHasmore()) returns true




回答2:


I find a solution by use expand operator. But, need to do some change on my API call. The response from the getApi2 need to return last page size and last page start.

    client.getApi1()
        .map(r -> r.getResult())
        .getApi2(p, 2, 1)
        .expand(res -> {
            if (res.isHasmore()) {
                return client.getApi2(orgId, res.getPageSize(), res.PageStart() + 1);
            }
            return Flux.empty();
        });


来源:https://stackoverflow.com/questions/52250893/how-to-use-reactor-spring-webclient-to-do-a-repeat-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!