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

defaultIfEmpty()

If we want to resort to a single emission if a given Observable comes out empty, we can use defaultIfEmpty(). For a given Observable<T>, we can specify a default T emission if no emissions occur when onComplete() is called.

If we have an Observable<String> and filter for items that start with Z but no items meet this criteria, we can resort to emitting None:

import io.reactivex.Observable;

public class Launcher {
public static void main(String[] args) {

Observable<String> items =
Observable.just("Alpha","Beta","Gamma","Delta","Epsilon");

items.filter(s -> s.startsWith("Z"))
.defaultIfEmpty("None")
.subscribe(System.out::println);
}
}

The output of the preceding code snippet is as follows:

None

Of course, if emissions were to occur, we would never see None emitted. It will only happen if the preceding Observable is empty.

主站蜘蛛池模板: 凌源市| 根河市| 大宁县| 桃江县| 永昌县| 宝鸡市| 商河县| 穆棱市| 汉阴县| 龙海市| 哈尔滨市| 潮安县| 积石山| 固阳县| 青冈县| 全州县| 晋城| 宁夏| 黄梅县| 晋中市| 伊春市| 民权县| 清涧县| 闽清县| 乐山市| 彩票| 兴山县| 稻城县| 白银市| 玉田县| 建水县| 比如县| 平乡县| 新竹县| 容城县| 黄陵县| 香河县| 织金县| 永城市| 郓城县| 汶上县|