如何并行调用多个Flowable语句?

huangapple go评论94阅读模式
英文:

How to call multiple Flowable statements in parallel?

问题

接口包含函数

  1. public interface XYZDownstreamService {
  2. Flowable<String> getData(Request request);
  3. }

以下是调用者

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

我想要同时执行上述的函数调用,以优化for循环。最佳的方法是什么?

英文:

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

  1. public Interface XYZDownstreamService {
  2. Flowable&lt;String&gt; getData(Request request);
  3. }

Below is the Caller

  1. public List&lt;String&gt; getDataFromDownstreamForRequests(List&lt;Request&gt; requests, XYZDownstreamService service) {
  2. List&lt;String&gt; dataFromDownstream = Lists.newArrayList();
  3. for(Request request: requests) {
  4. dataFromDownstream.add(service.getData(request).blockingFirst());
  5. }
  6. return dataFromDownstream;
  7. }

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

答案1

得分: 2

你只需要使用 merge 或者 flatMap 来合并你的请求。此外,可以使用不同的线程来处理你的请求,使用 observeOn

  1. Flowable.merge(requests
  2. .stream()
  3. .map(r -> service.getData(r)
  4. .observeOn(Schedulers.io())))
  5. .collect(toList())
  6. ).subscribe()

或者这样写:

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

我已经在一个类似的问题中回答过了,有更多的细节内容。

英文:

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

  1. Flowable.merge(requests
  2. .stream()
  3. .map(r -&gt; service.getData(r)
  4. .observeOn(Schedulers.io())))
  5. .collect(toList())
  6. ).subscribe()

Or write it like :

  1. Flowable.fromIterable(requests)
  2. .flatMap(r -&gt; service.getData(r)
  3. .observeOn(Schedulers.io()))
  4. .subscribe();

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

huangapple
  • 本文由 发表于 2020年10月21日 03:11:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64451859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定