RxJava MayBe Observable
MayBe类表示延迟响应。MayBe可观察对象可以发射单个成功值或者没有值。
类声明
以下是 **io.reactivex.Single
public abstract class Maybe<T>
extends Object
implements MaybeSource<T>
协议
下面是MayBe Observable操作的顺序协议:
onSubscribe (onSuccess | onError | OnComplete)?
MayBe的示例
使用任何你选择的编辑器,在C:>RxJava中创建以下Java程序。
ObservableTester.java
import java.util.concurrent.TimeUnit;
import io.reactivex.Maybe;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableMaybeObserver;
import io.reactivex.schedulers.Schedulers;
public class ObservableTester {
public static void main(String[] args) throws InterruptedException {
//Create an observer
Disposable disposable = Maybe.just("Hello World")
.delay(2, TimeUnit.SECONDS, Schedulers.io())
.subscribeWith(new DisposableMaybeObserver<String>() {
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onSuccess(String value) {
System.out.println(value);
}
@Override
public void onComplete() {
System.out.println("Done!");
}
});
Thread.sleep(3000);
//start observing
disposable.dispose();
}
}
验证结果
使用 javac 编译器编译该类,如下所示−
C:\RxJava>javac ObservableTester.java
现在按照以下步骤运行ObservableTester –
C:\RxJava>java ObservableTester
它应该产生以下输出 −
Hello World