RxJava2 中的条件可完成

Conditional Completable in RxJava2

我经常发现自己创建的流取决于 Single<Boolean> 提供的某些条件。考虑这个例子:

@Test
public void test() {
    Observable.range(0, 10)
            .flatMapSingle(this::shouldDoStuff)
            .flatMapCompletable(shouldDoStuff -> shouldDoStuff ? doStuff() : Completable.complete())
            .test();
}

private Single<Boolean> shouldDoStuff(int number) {
    return Single.just(number % 2 == 0);
}

private Completable doStuff() {
    return Completable.fromAction(() -> System.out.println("Did stuff"));
}

我发现 flatMapSingle(...).flatMapCompletable(...) 部分不必要冗长。

也许有可用的运算符可以简化这个,例如:

Observable.range(0, 10)
        .flatMapSingle(this::shouldDoStuff)
        .flatMapCompletableIfTrue(doStuff())
        .test();

或者一个包含两行的静态构造函数,例如:

Observable.range(0, 10)
        .flatMapCompletable(number -> Completable.ifTrue(shouldDoStuff(number), doStuff()))
        .test();

如果这种条件检查将成为您的许多流的一部分,请告诉我您将如何实施。

您可以对 shouldDoStuff

的结果使用 filter 运算符
 Observable.range(0, 10)
            .flatMapSingle(this::shouldDoStuff)
            .filter(shouldDo -> shouldDo)  // this will emit to the downstream only if shouldDo = true
            .flatMapCompletable(__ -> doStuff())
            .test();

或者尝试编写包装器以使代码更具可读性,(通过将相同的逻辑移动到包装器)

  class CompletableIfTrue {
    public static CompletableSource when(Single<Boolean> shouldDoStuff, Completable doStuff) {
        return shouldDoStuff.flatMapCompletable(shouldDo -> shouldDo ? doStuff : Completable.complete());
    }

Observable.range(0, 10)
     .flatMapCompletable(number -> CompletableIfTrue.when(shouldDoStuff(number), doStuff()))
     .test();