- Learning RxJava
- Thomas Nield
- 140字
- 2021-07-02 22:22:58
switchIfEmpty()
Similar to defaultIfEmpty(), switchIfEmpty() specifies a different Observable to emit values from if the source Observable is empty. This allows you specify a different sequence of emissions in the event that the source is empty rather than emitting just one value.
We could choose to emit three additional strings, for example, if the preceding Observable came out empty due to a filter() operation:
import io.reactivex.Observable;
public class Launcher {
public static void main(String[] args) {
Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
.filter(s -> s.startsWith("Z"))
.switchIfEmpty(Observable.just("Zeta", "Eta", "Theta"))
.subscribe(i -> System.out.println("RECEIVED: " + i),
e -> System.out.println("RECEIVED ERROR: " + e)
);
}
}
The output of the preceding code snippet is as follows:
RECEIVED: Zeta
RECEIVED: Eta
RECEIVED: Theta
Of course, if the preceding Observable is not empty, then switchIfEmpty() will have no effect and not use that specified Observable.
推薦閱讀
- 基于粒計算模型的圖像處理
- Mastering Zabbix(Second Edition)
- Java 9 Concurrency Cookbook(Second Edition)
- PyTorch自動駕駛視覺感知算法實戰
- C語言程序設計實訓教程
- PHP+MySQL網站開發項目式教程
- Spring核心技術和案例實戰
- Android系統級深入開發
- C語言程序設計習題與實驗指導
- OpenCV with Python Blueprints
- 程序員必會的40種算法
- Elasticsearch Blueprints
- Android項目實戰:博學谷
- HTML5 Game Development by Example:Beginner's Guide(Second Edition)
- Visual Basic 開發從入門到精通