Rxjava 简明教程

RxJava - MayBe Observable

MayBe 类表示延迟响应。MayBe 可观察对象可以发出一个成功的单个值或不发出值。

Class Declaration

以下为 io.reactivex.Single<T> 类的声明:

public abstract class Maybe<T>
   extends Object
      implements MaybeSource<T>

Protocol

下面是 MayBe 可观察对象的操作顺序——

onSubscribe (onSuccess | onError | OnComplete)?

MayBe Example

在任意编辑器中使用任何您选择的语言(如 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();
   }
}

Verify the Result

按照如下方式使用 javac 编译器编译类 −

C:\RxJava>javac ObservableTester.java

现在按照如下所示运行 ObservableTester:

C:\RxJava>java ObservableTester

它应该产生以下输出 −

Hello World