RxJava2 并行执行一堆可操作,并等待所有操作完成

2022-09-03 10:13:17

我想执行几种阻塞方法(网络调用,计算任务)。我想并行执行它们,并在它们全部完成时收到通知,或者如果其中任何一个失败(引发异常)收到错误。他们不会发出结果,所以不会帮助我。Observable.zip()

到目前为止,我有:

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

然而,文档说.我没有找到一个可以并行执行它们的解决方案。Completable.concat()Returns a Completable which completes only when all sources complete, one after another.


答案 1

您可能希望使用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 :( */ }
);

答案 2

推荐