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

  • Learning RxJava
  • Thomas Nield
  • 125字
  • 2021-07-02 22:22:58

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.

主站蜘蛛池模板: 嵩明县| 拉萨市| 合水县| 调兵山市| 河津市| 化德县| 繁昌县| 鄂温| 阜阳市| 拉萨市| 白玉县| 天津市| 宁陵县| 内乡县| 武城县| 陆河县| 库伦旗| 溆浦县| 洛川县| 孟州市| 红河县| 屯留县| 许昌县| 确山县| 建始县| 汶上县| 蕲春县| 和平区| 东阳市| 天水市| 九龙坡区| 镇江市| 秦安县| 曲沃县| 米脂县| 漳州市| 麟游县| 新野县| 冷水江市| 鱼台县| 肃宁县|