官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 夏津县| 琼结县| 浦江县| 沭阳县| 类乌齐县| 内江市| 嵊州市| 广州市| 海兴县| 鹤岗市| 共和县| 浦城县| 资源县| 永昌县| 木兰县| 兴化市| 凤阳县| 安康市| 九寨沟县| 苏尼特右旗| 浦县| 麻城市| 衡东县| 光泽县| 呼伦贝尔市| 长葛市| 安义县| 库伦旗| 灵丘县| 邢台市| 平果县| 长兴县| 讷河市| 扶风县| 饶河县| 拜城县| 新龙县| 中阳县| 贵定县| 遂昌县| 甘德县|