[英]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();
或者嘗試編寫一個包裝器以使代碼更具可讀性,(通過將相同的邏輯移至 wrapper )
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.