问题
I am using several filters on my Observable and I would like to report cases at the end of filtering when the result was empty. I cannot do it at the end of processing because this observable is supposed to be concatenated with another one:
Observable.just(1, 2, 3)
.concatWith(
Observable.just(2, 4, 6)
.filter(value -> ((value % 2) != 0))
// report if empty
)
回答1:
You can use Transformers.doOnEmpty from rxjava-extras which is on Maven Central:
source.compose(Transformers.doOnEmpty(action))
You might use this solution if you cared about efficiency (allocations/performance) but otherwise use @dwursteisen's solution.
回答2:
You can use switchIfEmpty and do something with this fallback Observable
Observable.just(2, 4, 6)
.filter(value -> ((value % 2) != 0))
// replace the empty observable with an empty observable
// but this observable will log when it will completed
.switchIfEmpty(Observable.<Integer>empty().doOnTerminate(() -> System.out.println("empty !")))
.subscribe();
来源:https://stackoverflow.com/questions/38721991/rxjava-how-to-code-something-like-doonempty