【问题标题】:Conditional Completable in RxJava2RxJava2 中的条件可完成
【发布时间】:2019-11-25 10:18:12
【问题描述】:

我经常发现自己创建的流取决于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();

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

【问题讨论】:

    标签: java rx-java rx-java2


    【解决方案1】:

    您可以对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();
    

    【讨论】:

    • 感谢您的建议。不幸的是,filter 方法更加冗长。此外,它还可以防止事件向下游传播。我知道在这个简单的示例中这没有问题,但是想象一下如果流有多个条件或者只是在.test() 之前继续,则需要嵌套
    • 如果你使用 Kotlin,你可以使用扩展函数 ifTrueCompletable 类。在 java 中,可能你可以为此目的编写一个包装类,这将使代码更具可读性。这只是一个建议,不确定它是否完全符合您的要求。请查看更新后的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多