RxJava - Maybe Observable



The Maybe class represents deferred response. Maybe observable can emit either a single successful value or no value.

Class Declaration

Following is the declaration for io.reactivex.rxjava3.core.Maybe<T> class −

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

Protocol

Following is the sequential protocol that Single Observable operates −

onSubscribe (onSuccess | onError | OnComplete)?

Example - Creating a MayBe Observable Class to get Data

ObservableTester.java

package com.tutorialspoint;

import io.reactivex.rxjava3.core.Maybe;

public class ObservableTester  {
   public static void main(String[] args)  throws InterruptedException {
      Maybe.just("Hello world").subscribe(System.out::println);
   }
}

Output

Compile and Run the code to verify the following output −

Hello World

Example - Usage of Maybe Observable Class to get Data after a delay of 2 seconds

ObservableTester.java

package com.tutorialspoint;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.observers.DisposableMaybeObserver;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class ObservableTester  {
   public static void main(String[] args)  throws InterruptedException {
      //Create the observable
      Maybe<String> testMaybe = Maybe.just("Hello World");

      //Create an observer
      Disposable disposable = testMaybe
         .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();
   }
}

Output

Compile and Run the code to verify the following output −

Hello World
Advertisements