RxJava2中的条件条件可完成

问题描述 投票:1回答:1

我经常发现自己创建的流取决于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个回答
1
投票

您可以对filter的结果使用shouldDoStuff运算符>

 Observable.range(0, 10)
            .flatMapSingle(this::shouldDoStuff)
            .filter(shouldDo -> shouldDo)  // this will emit to the downstream only if shouldDo = true
            .flatMapCompletable(__ -> doStuff())
            .test();
© www.soinside.com 2019 - 2024. All rights reserved.