问题
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
}
回答1:
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()
}
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
Also check this article about parallelization - http://tomstechnicalblog.blogspot.ru/2015/11/rxjava-achieving-parallelization.html
来源:https://stackoverflow.com/questions/42804801/how-to-invoke-a-method-for-each-element-in-a-collection-parallely-using-rxjava