英文:
How to call multiple Flowable statements in parallel?
问题
接口包含函数
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;
}
我想要同时执行上述的函数调用,以优化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
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
得分: 2
你只需要使用 merge
或者 flatMap
来合并你的请求。此外,可以使用不同的线程来处理你的请求,使用 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();
我已经在一个类似的问题中回答过了,有更多的细节内容。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论