RxJava2 Flowable switchIfEmpty(条件操作符)

switchIfEmpty

目录

1 switchIfEmpty接口

2 重点单词 

3 switchIfEmpty测试用例

4 switchIfEmpty测试用例说明

5 switchIfEmpty总结


1 switchIfEmpty接口

Flowable<T> switchIfEmpty(Publisher<? extends T> other)

Returns a Flowable that emits the items emitted by the source Publisher or the items of an alternate Publisher if the source Publisher is empty.

返回一个Flowable,如果源Publisher为空,则会发出源Publisher发出的项或备用Publisher的项

2 重点单词 

alternate [ˈɔ:ltərnət]

  • vi. 交替;轮流;相见;变换;交叉;迭;错;穿插。
  • vt. 使交替;使轮流
  • adj. 交替的;轮流的;备用的
  • n. 代替者

3 switchIfEmpty测试用例

测试用例
@Test
    public void switchIfEmpty() {
        System.out.println("######debounce#####");
        Flowable alternate = Flowable.just("备选方案1","备选方案2");

        Flowable.just("主方案")
                .switchIfEmpty(alternate)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        System.out.println("o = " + o);
                    }
                });

        System.out.println("#如果Flowable为空时#");
        
        Flowable.empty()
                .switchIfEmpty(alternate)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        System.out.println("o = " + o);
                    }
                });
    }


测试结果
######debounce#####
o = 主方案
#如果Flowable为空时#
o = 备选方案1
o = 备选方案2

4 switchIfEmpty测试用例说明

上面测试用中在如果我们的Publisher不是空,则备选方案是不会启用的

5 switchIfEmpty总结

这里把switchIfEmpty提前到这里分析有助于理解,defaultIfEmpty操作符是在Publisher不发送数据时发送一个默认的数据,如果在同样的条件下需要发送更多数据,switchIfEmpty操作符是个更好的选择,可以发送一个自定的Publisher,可以比较两者传入参数类型。

猜你喜欢

转载自blog.csdn.net/weixin_36709064/article/details/82949453
今日推荐