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

Maybe

Maybe is just like a Single except that it allows no emission to occur at all (hence Maybe). MaybeObserver is much like a standard Observer, but onNext() is called onSuccess() instead:

      public interface MaybeObserver<T> {
void onSubscribe(Disposable d);
void onSuccess(T value);
void onError(Throwable e);
void onComplete();
}

A given Maybe<T> will only emit 0 or  1 emissions. It will pass the possible emission to onSuccess(), and in either case, it will call onComplete() when done. Maybe.just() can be used to create a Maybe emitting the single item. Maybe.empty() will create a Maybe that yields no emission:

    import io.reactivex.Maybe;

public class Launcher {

public static void main(String[] args) {

// has emission
Maybe<Integer> presentSource = Maybe.just(100);

presentSource.subscribe(s -> System.out.println("Process 1
received: "
+ s),
Throwable::printStackTrace,
() -> System.out.println("Process 1 done!"));

//no emission
Maybe<Integer> emptySource = Maybe.empty();

emptySource.subscribe(s -> System.out.println("Process 2
received: "
+ s),
Throwable::printStackTrace,
() -> System.out.println("Process 2 done!"));
}
}

 The output is as follows:

    Process 1 received: 100
Process 2 done!

Certain Observable operators that we will learn about later yield a Maybe. One example is the firstElement() operator, which is similar to first(), but it returns an empty result if no elements are emitted:

    import io.reactivex.Observable;

public class Launcher {

public static void main(String[] args) {

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

source.firstElement().subscribe(
s -> System.out.println("RECEIVED " + s),
Throwable::printStackTrace,
() -> System.out.println("Done!"));
}
}

 The output is as follows:

    RECEIVED Alpha
主站蜘蛛池模板: 和田市| 丰镇市| 孝昌县| 永仁县| 白银市| 墨竹工卡县| 山阳县| 海伦市| 启东市| 江达县| 梅州市| 涞水县| 岗巴县| 绥化市| 姚安县| 洞头县| 宣威市| 斗六市| 开封市| 长白| 鱼台县| 德钦县| 宁武县| 南乐县| 西平县| 竹北市| 兴和县| 尚义县| 桃园县| 庆城县| 巴里| 德兴市| 民和| 尤溪县| 湘西| 湘阴县| 柘荣县| 芜湖市| 甘孜县| 望谟县| 泌阳县|