Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava2 execute bunch of Completables in parallel and wait all to complete

I want to execute several blocking methods (network calls, computation tasks). I want to execute them in parallel and be notified when ALL of them complete or receive an error if ANY of them fails (throws an exception). They do not emit results so Observable.zip() is not going to help me.

So far I have:

Completable a = computationTaskA();
Completable b = computationTaskB();
Completable c = computationTaskC();
Completable all = Completable.concat(Arrays.asList(a, b, c))
            .subscribe(() -> {
               // all succeed
            }, e -> {
               // any fails
            });

However Completable.concat() docs say Returns a Completable which completes only when all sources complete, one after another.. I do not find a solution that would execute them in parallel.

like image 323
ddinchev Avatar asked Mar 20 '18 14:03

ddinchev


1 Answers

You probably want to use Completable.merge/mergeArray

Completable a = computationTaskA();
Completable b = computationTaskB();
Completable c = computationTaskC();
Completable all = Completable.mergeArray(a, b, c);

all.subscribe(
    () -> { /* success all around! */ },
    e -> { /* at least one failure :( */ }
);
like image 188
marianosimone Avatar answered Nov 12 '22 20:11

marianosimone