Combine a list of Observables and wait until all completed

前端 未结 8 1094
爱一瞬间的悲伤
爱一瞬间的悲伤 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:59

    Of the suggestions proposed, zip() actually combines observable results with each other, which may or may not be what is wanted, but was not asked in the question. In the question, all that was wanted was execution of each of the operations, either one-by-one or in parallel (which was not specified, but linked Bolts example was about parallel execution). Also, zip() will complete immediately when any of the observables complete, so it's in violation of the requirements.

    For parallel execution of Observables, flatMap() presented in the other answer is fine, but merge() would be more straight-forward. Note that merge will exit on error of any of the Observables, if you rather postpone the exit until all observables have finished, you should be looking at mergeDelayError().

    For one-by-one, I think Observable.concat() static method should be used. Its javadoc states like this:

    concat(java.lang.Iterable> sequences) Flattens an Iterable of Observables into one Observable, one after the other, without interleaving them

    which sounds like what you're after if you don't want parallel execution.

    Also, if you're only interested in the completion of your task, not return values, you should probably look into Completable instead of Observable.

    TLDR: for one-by-one execution of tasks and oncompletion event when they are completed, I think Completable.concat() is best suited. For parallel execution, Completable.merge() or Completable.mergeDelayError() sounds like the solution. The former one will stop immediately on any error on any completable, the latter one will execute them all even if one of them has an error, and only then reports the error.

提交回复
热议问题