如何并行调用多个Flowable语句? [英] How to call multiple Flowable statements in parallel?

查看:109
本文介绍了如何并行调用多个Flowable语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些返回Flowable对象的函数调用.我必须多次调用此函数,并且此函数正在执行一些网络调用.我想同时进行所有这些调用.下面是代码.

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.

包含该功能的接口

public Interface XYZDownstreamService {

  Flowable<String> getData(Request request);
}

下面是呼叫者

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?

推荐答案

您只需要使用 merge flatMap 合并您的请求.此外,使用不同的线程通过 observeOn 处理您的请求.

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()

或者像这样写:

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

我已经回答了类似问题,以获取更多详细信息.

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

这篇关于如何并行调用多个Flowable语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆