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

  • Learning RxJava
  • Thomas Nield
  • 240字
  • 2021-07-02 22:22:55

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
主站蜘蛛池模板: 雷州市| 大化| 惠水县| 从化市| 丰镇市| 武穴市| 宜州市| 宜兰县| 本溪市| 牡丹江市| 汨罗市| 长顺县| 渭南市| 安龙县| 绍兴市| 东海县| 庐江县| 庆元县| 新余市| 台湾省| 东宁县| 同仁县| 陆良县| 砀山县| 抚宁县| 太白县| 永福县| 枝江市| 望江县| 临西县| 米易县| 庆安县| 兰州市| 五河县| 武威市| 偃师市| 康定县| 马鞍山市| 元谋县| 南宫市| 界首市|