How to call multiple Flowable statements in parallel?

我只是一个虾纸丫 提交于 2021-01-29 18:12:55

问题


I have a few function calls that return Flowable object. I have to call this function multiple times and this function is doing some network calls. I want to do all these calls concurrently. Below is the code.

Interface containing the function

public Interface XYZDownstreamService {

  Flowable<String> getData(Request request);
}

Below is the Caller

public List<String> getDataFromDownstreamForRequests(List<Request> requests, XYZDownstreamService service) {
    List<String> dataFromDownstream = Lists.newArrayList();
    for(Request request: requests) {
        dataFromDownstream.add(service.getData(request).blockingFirst());
    }
    return dataFromDownstream;
}

I want to do the above function calls concurrently to optimize the for a loop. What is the best way to do it?


回答1:


You just need to merge your requests using merge or flatMap. Moreover, use a diffrent threads to process your requests using observeOn.

Flowable.merge(requests
  .stream()
  .map(r -> service.getData(r)
              .observeOn(Schedulers.io())))
  .collect(toList())
).subscribe()

Or write it like :

Flowable.fromIterable(requests)
        .flatMap(r -> service.getData(r)
                .observeOn(Schedulers.io()))
        .subscribe();

I've already reply to a similar question for more details.



来源:https://stackoverflow.com/questions/64451859/how-to-call-multiple-flowable-statements-in-parallel

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