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

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.

主站蜘蛛池模板: 蒲江县| 井冈山市| 横山县| 师宗县| 含山县| 台北县| 绥江县| 饶河县| 连州市| 吉林市| 正安县| 多伦县| 南召县| 隆化县| 双辽市| 丽江市| 中西区| 婺源县| 临潭县| 天镇县| 马鞍山市| 洞口县| 锦屏县| 司法| 乐亭县| 交口县| 拜泉县| 浙江省| 明水县| 德令哈市| 土默特左旗| 金门县| 巴彦淖尔市| 隆尧县| 涞源县| 刚察县| 府谷县| 扶沟县| 黑山县| 措美县| 湘阴县|