Combine a list of Observables and wait until all completed

前端 未结 8 1119
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 06:35

TL;DR How to convert Task.whenAll(List) into RxJava?

My existing code uses Bolts to build up a list of asynchr

8条回答
  •  孤街浪徒
    2020-12-04 06:54

    You can use flatMap in case you have dynamic tasks composition. Something like this:

    public Observable whenAll(List> tasks) {
        return Observable.from(tasks)
                //execute in parallel
                .flatMap(task -> task.observeOn(Schedulers.computation()))
                //wait, until all task are executed
                //be aware, all your observable should emit onComplemete event
                //otherwise you will wait forever
                .toList()
                //could implement more intelligent logic. eg. check that everything is successful
                .map(results -> true);
    }
    

    Another good example of parallel execution

    Note: I do not really know your requirements for error handling. For example what to do if only one task fails. I think you should verify this scenario.

提交回复
热议问题