RxJava: how to code something like doOnEmpty?

走远了吗. 提交于 2019-12-08 03:28:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!