How to call a method for each item in a collection in parallel using RxJava
I have two methods and need to call findDetails (name) method in parallel for all names in the list. How can this be achieved with RxJava? Basically I want to call the findDetails method on each item in the collection on different threads.
public List<Bean> findStudentDetails(List<String> names){
names.forEach(s->{
findDetails(s);
});
}
private Bean findDetails(String name){
//some io operation
}
source to share
Make your methods return Observable
, then flatMap
yours Observables
with an applied operator subscribeOn
:
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()
}
Note : The computation Scheduler
limits the number of threads counted by the number of available processor cores to improve performance under intensive operations. For more information check out this excellent answer about Schedulers
- fooobar.com/questions/36080 / ...
Also check this article on parallelization - http://tomstechnicalblog.blogspot.ru/2015/11/rxjava-achieving-parallelization.html
source to share