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

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.

主站蜘蛛池模板: 南皮县| 玉山县| 太和县| 正阳县| 西林县| 泸定县| 连平县| 宜州市| 韶山市| 聂荣县| 辽阳县| 神木县| 金平| 日土县| 黑山县| 开化县| 靖西县| 大英县| 明溪县| 林芝县| 河津市| 南部县| 阆中市| 南丹县| 泉州市| 乌鲁木齐县| 长兴县| 贞丰县| 怀宁县| 开江县| 即墨市| 酒泉市| 马山县| 津市市| 巴青县| 万年县| 哈尔滨市| 西青区| 溆浦县| 遂昌县| 江阴市|