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

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.

主站蜘蛛池模板: 棋牌| 洪洞县| 石林| 内江市| 葵青区| 大同县| 太湖县| 专栏| 西乌| 霍林郭勒市| 吴川市| 温州市| 杨浦区| 错那县| 东阳市| 西宁市| 荥经县| 庆阳市| 江西省| 仙游县| 东平县| 两当县| 甘肃省| 武邑县| 安顺市| 纳雍县| 浦城县| 常州市| 唐河县| 嵊州市| 会同县| 信丰县| 宝山区| 乌兰察布市| 通道| 龙岩市| 珠海市| 永济市| 安仁县| 东乡县| 杭州市|