如何使用 RxJava 为集合中的每个元素并行调用方法 [英] How to invoke a method for each element in a collection parallely using RxJava
问题描述
我有以下两种方法,需要为列表中的所有名称并行调用 findDetails(name) 方法.如何使用 RxJava 实现这一点?基本上我想为不同线程中集合中的每个元素调用 findDetails 方法.
I have below two methods and need to invoke findDetails(name) method parallely for all names in the list. How can achieve this using RxJava? Basically I want to invoke findDetails method for each element in teh collection in diffrent threads.
public List<Bean> findStudentDetails(List<String> names){
names.forEach(s->{
findDetails(s);
});
}
private Bean findDetails(String name){
//some io operation
}
推荐答案
使你的方法返回 Observable
,然后 flatMap
你的 Observables
应用 subscribeOn
运算符:
Make your methods to return Observable
, then flatMap
your Observables
with applied subscribeOn
operator:
private Observable<Bean> findDetails(String name) {
return Observable.fromCallable(() -> { //or any other creation method
//some io operation
}
}
public Observable<List<Bean>> findStudentDetails(List<String> names) {
return Observable.from(names)
.flatMap(s -> findDetails(s).subscribeOn(Schedulers.computation())
.toList()
}
注意:计算 Scheduler
将线程数限制为可用 CPU 内核的数量,以便在密集操作中获得更好的性能.有关更多信息,请查看有关 Schedulers
的精彩答案 - https://stackoverflow.com/a/31282775/7045114
Note: computation Scheduler
limits threads count to the number of available CPU cores for better performance on intense operations. For more information check this great answer about Schedulers
- https://stackoverflow.com/a/31282775/7045114
另请查看这篇关于并行化的文章 - http://tomstechnicalblog.blogspot.ru/2015/11/rxjava-achieving-parallelization.html
Also check this article about parallelization - http://tomstechnicalblog.blogspot.ru/2015/11/rxjava-achieving-parallelization.html
这篇关于如何使用 RxJava 为集合中的每个元素并行调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!