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

  • 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.

主站蜘蛛池模板: 内江市| 南部县| 额济纳旗| 郎溪县| 祁门县| 浦江县| 南陵县| 讷河市| 镇沅| 久治县| 景泰县| 娄底市| 连江县| 巴林右旗| 丰原市| 罗江县| 京山县| 绥棱县| 凤冈县| 耒阳市| 金塔县| 龙门县| 华坪县| 凌云县| 如皋市| 屏边| 明水县| 湘乡市| 武宣县| 绩溪县| 铜川市| 文化| 乡城县| 柘城县| 山东省| 怀安县| 阿拉善盟| 呼和浩特市| 枣庄市| 常德市| 邵东县|