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

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.

主站蜘蛛池模板: 易门县| 珲春市| 辰溪县| 阿克陶县| 尼勒克县| 宜兰县| 北宁市| 汪清县| 乐东| 手机| 独山县| 天柱县| 沅陵县| 武清区| 偃师市| 芜湖县| 长兴县| 元江| 凯里市| 黑山县| 梓潼县| 城固县| 武夷山市| 易门县| 涞源县| 安阳市| 年辖:市辖区| 清远市| 拜城县| 孙吴县| 宁阳县| 安化县| 丽水市| 巴东县| 洛南县| 吕梁市| 垣曲县| 信阳市| 郧西县| 临沂市| 易门县|