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

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.

主站蜘蛛池模板: 鄂伦春自治旗| 从化市| 永泰县| 余姚市| 城口县| 留坝县| 抚顺县| 枝江市| 宜章县| 鲁甸县| 甘肃省| 大埔区| 雷州市| 五莲县| 蕲春县| 施甸县| 屏南县| 安顺市| 蒙城县| 北碚区| 高州市| 鄂伦春自治旗| 象州县| 泽库县| 延寿县| 盐源县| 巍山| 乳源| 南江县| 布拖县| 潢川县| 泰州市| 黑山县| 翁牛特旗| 和林格尔县| 嘉义市| 肥乡县| 诸暨市| 桓仁| 镇安县| 邵阳县|