- Learning RxJava
- Thomas Nield
- 125字
- 2021-07-02 22:22:58
defaultIfEmpty()
If we want to resort to a single emission if a given Observable comes out empty, we can use defaultIfEmpty(). For a given Observable<T>, we can specify a default T emission if no emissions occur when onComplete() is called.
If we have an Observable<String> and filter for items that start with Z but no items meet this criteria, we can resort to emitting None:
import io.reactivex.Observable;
public class Launcher {
public static void main(String[] args) {
Observable<String> items =
Observable.just("Alpha","Beta","Gamma","Delta","Epsilon");
items.filter(s -> s.startsWith("Z"))
.defaultIfEmpty("None")
.subscribe(System.out::println);
}
}
The output of the preceding code snippet is as follows:
None
Of course, if emissions were to occur, we would never see None emitted. It will only happen if the preceding Observable is empty.
推薦閱讀
- Learning Microsoft Windows Server 2012 Dynamic Access Control
- Cocos2d-x游戲開發(fā):手把手教你Lua語言的編程方法
- Visual Basic編程:從基礎(chǔ)到實踐(第2版)
- Production Ready OpenStack:Recipes for Successful Environments
- 精通軟件性能測試與LoadRunner實戰(zhàn)(第2版)
- TypeScript圖形渲染實戰(zhàn):基于WebGL的3D架構(gòu)與實現(xiàn)
- SQL經(jīng)典實例(第2版)
- UNIX Linux程序設(shè)計教程
- Odoo 10 Implementation Cookbook
- JavaScript悟道
- Mastering Embedded Linux Programming
- 人人都能開發(fā)RPA機(jī)器人:UiPath從入門到實戰(zhàn)
- Solr權(quán)威指南(下卷)
- Apache Solr for Indexing Data
- Android開發(fā)權(quán)威指南(第二版)