- 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.
推薦閱讀
- Implementing VMware Horizon 7(Second Edition)
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- JavaScript高效圖形編程
- 編程的修煉
- Rust編程:入門、實戰與進階
- Python自動化運維快速入門(第2版)
- 程序員面試算法寶典
- Python從菜鳥到高手(第2版)
- 青少年Python編程入門
- Spring Boot進階:原理、實戰與面試題分析
- PHP+MySQL+Dreamweaver動態網站開發從入門到精通(第3版)
- Mastering Data Mining with Python:Find patterns hidden in your data
- 21天學通C++(第5版)
- Python Data Science Cookbook
- ActionScript 3.0從入門到精通(視頻實戰版)