2

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
         } 
Christoph
  • 3,980
  • 2
  • 40
  • 41
Raj
  • 115
  • 8

1 Answers1

2

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

Community
  • 1
  • 1
Maksim Ostrovidov
  • 10,720
  • 8
  • 42
  • 57