1. 程式人生 > >RxJava2 Flowable switchIfEmpty(條件操作符)

RxJava2 Flowable switchIfEmpty(條件操作符)

switchIfEmpty

目錄

2 重點單詞 

1 switchIfEmpty介面

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,可以比較兩者傳入引數型別。