How to invoke a method for each element in a collection parallely using RxJava

天大地大妈咪最大 提交于 2019-12-22 12:45:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!