- 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.
推薦閱讀
- Puppet 4 Essentials(Second Edition)
- Learn TypeScript 3 by Building Web Applications
- Node.js 10實戰
- VMware vSphere 6.7虛擬化架構實戰指南
- Python Tools for Visual Studio
- Python 3網絡爬蟲實戰
- Visual Basic程序設計與應用實踐教程
- TradeStation交易應用實踐:量化方法構建贏家策略(原書第2版)
- Integrating Facebook iOS SDK with Your Application
- Android玩家必備
- Spring Boot+Vue全棧開發實戰
- 零基礎學Kotlin之Android項目開發實戰
- 編程改變生活:用Python提升你的能力(進階篇·微課視頻版)
- Ext JS 4 Plugin and Extension Development
- 會當凌絕頂:Java開發修行實錄