- Learning RxJava
- Thomas Nield
- 140字
- 2021-07-02 22:22:58
switchIfEmpty()
Similar to defaultIfEmpty(), switchIfEmpty() specifies a different Observable to emit values from if the source Observable is empty. This allows you specify a different sequence of emissions in the event that the source is empty rather than emitting just one value.
We could choose to emit three additional strings, for example, if the preceding Observable came out empty due to a filter() operation:
import io.reactivex.Observable;
public class Launcher {
public static void main(String[] args) {
Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
.filter(s -> s.startsWith("Z"))
.switchIfEmpty(Observable.just("Zeta", "Eta", "Theta"))
.subscribe(i -> System.out.println("RECEIVED: " + i),
e -> System.out.println("RECEIVED ERROR: " + e)
);
}
}
The output of the preceding code snippet is as follows:
RECEIVED: Zeta
RECEIVED: Eta
RECEIVED: Theta
Of course, if the preceding Observable is not empty, then switchIfEmpty() will have no effect and not use that specified Observable.
推薦閱讀
- 自己動手寫搜索引擎
- Building Mobile Applications Using Kendo UI Mobile and ASP.NET Web API
- Visual Basic程序設計習題解答與上機指導
- 嚴密系統設計:方法、趨勢與挑戰
- Access 2016數據庫管
- Android 應用案例開發大全(第3版)
- Learning Data Mining with R
- Web Development with MongoDB and Node(Third Edition)
- Mastering Xamarin.Forms(Second Edition)
- OpenCV 4計算機視覺項目實戰(原書第2版)
- JSP程序設計實例教程(第2版)
- 計算機應用基礎項目化教程
- Troubleshooting Citrix XenApp?
- Python Projects for Kids
- JavaScript編程精解(原書第2版)