- 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.
推薦閱讀
- Oracle WebLogic Server 12c:First Look
- JSP網絡編程(學習筆記)
- Web交互界面設計與制作(微課版)
- 我的第一本算法書
- Java游戲服務器架構實戰
- Flash CS6中文版應用教程(第三版)
- GameMaker Programming By Example
- Unity 3D/2D移動開發實戰教程
- R用戶Python學習指南:數據科學方法
- Java編程從入門到精通
- Mastering Elixir
- Web程序設計:ASP.NET(第2版)
- 零基礎學C++(升級版)
- Android Studio開發實戰:從零基礎到App上線 (移動開發叢書)
- 人人都能開發RPA機器人:UiPath從入門到實戰