有条件地完成链

Chain Completables conditionally

为什么RxJava在条件后面加第三个completable(completable3)不执行?

我注意到这并不是链似乎被破坏的唯一情况,所以我想知道以下代码无法按预期执行的根本原因。

Completable chain = completable1
    .andThen(completable2);

if(condition)
    chain.andThen(completable3);

chain.subscribe();

我知道我可以做类似的事情:

completable1
    .andThen(completable2);
    .andThen(Completable.defer(() => {
        if(condition)
            return completable3;
        else 
            return Completable.complete();
    }))
    .subscribe();

RxJava 中的运算符 return 您应该继续编写的新实例,因此,忽略 returned Completable 会导致无操作。你在第二个例子中做对了。对于第一个示例,您可以将链引用替换为调制实例 returned by andThen:

Completable chain = completable1
    .andThen(completable2);

if (condition) {
    chain = chain.andThen(completable3);
}

chain.subscribe();