- 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.
推薦閱讀
- Practical Data Analysis Cookbook
- 數據科學實戰手冊(R+Python)
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- C# Programming Cookbook
- Android 7編程入門經典:使用Android Studio 2(第4版)
- Flux Architecture
- Elasticsearch for Hadoop
- Asynchronous Android Programming(Second Edition)
- Java Fundamentals
- Java程序設計與項目案例教程
- Python程序設計開發寶典
- Python函數式編程(第2版)
- 零基礎學C++(升級版)
- Java程序設計教程
- 會當凌絕頂:Java開發修行實錄