- 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
推薦閱讀
- Spring 5.0 Microservices(Second Edition)
- Visual Basic .NET程序設(shè)計(jì)(第3版)
- Android 9 Development Cookbook(Third Edition)
- Visual Basic程序設(shè)計(jì)習(xí)題解答與上機(jī)指導(dǎo)
- Xamarin.Forms Projects
- C++新經(jīng)典
- WordPress 4.0 Site Blueprints(Second Edition)
- 零基礎(chǔ)Java學(xué)習(xí)筆記
- C#程序設(shè)計(jì)教程(第3版)
- 搞定J2EE:Struts+Spring+Hibernate整合詳解與典型案例
- Unity&VR游戲美術(shù)設(shè)計(jì)實(shí)戰(zhàn)
- Arduino電子設(shè)計(jì)實(shí)戰(zhàn)指南:零基礎(chǔ)篇
- 超好玩的Scratch 3.5少兒編程
- 原型設(shè)計(jì):打造成功產(chǎn)品的實(shí)用方法及實(shí)踐
- ASP.NET本質(zhì)論