- 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.
推薦閱讀
- Learn ECMAScript(Second Edition)
- iOS Game Programming Cookbook
- Spring 5企業級開發實戰
- Rust實戰
- HTML5游戲開發案例教程
- Hands-On GPU:Accelerated Computer Vision with OpenCV and CUDA
- C#程序設計(項目教學版)
- Python+Tableau數據可視化之美
- Node.js開發指南
- 3ds Max印象 電視欄目包裝動畫與特效制作
- Mastering Elixir
- C語言程序設計實踐
- Android 游戲開發大全(第二版)
- SQL Server 2014 Development Essentials
- Java Web入門很輕松(微課超值版)