- 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 Python Web Penetration Testing
- Visual FoxPro程序設計教程
- Web Scraping with Python
- 區塊鏈架構與實現:Cosmos詳解
- Java程序員面試算法寶典
- Hands-On GPU:Accelerated Computer Vision with OpenCV and CUDA
- 從0到1:Python數據分析
- PHP 7+MySQL 8動態網站開發從入門到精通(視頻教學版)
- Python Data Analysis Cookbook
- 蘋果的產品設計之道:創建優秀產品、服務和用戶體驗的七個原則
- 愛上micro:bit
- WildFly Cookbook
- SEO教程:搜索引擎優化入門與進階(第3版)
- Mastering R for Quantitative Finance
- Instant Buildroot