- 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.
推薦閱讀
- iOS 9 Game Development Essentials
- Visual C++數字圖像模式識別技術詳解
- 羅克韋爾ControlLogix系統應用技術
- Learning ArcGIS Pro
- Unity Shader入門精要
- GameMaker Programming By Example
- NGINX Cookbook
- Apache Solr PHP Integration
- 零基礎學C++(升級版)
- Mastering OpenStack
- Splunk Essentials
- Java面試一戰到底(基礎卷)
- OpenStack Sahara Essentials
- ROS Robotics Projects
- 數據預處理從入門到實戰:基于SQL、R、Python