RxJava - MayBe Observable

MayBe 类表示延迟响应。MayBe observable 可以发出单个成功值或不发出任何值。

类声明

以下是 io.reactivex.Single<T> 类的声明 −

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