RxJava - Single Observable

Single is an observable that emits only a single item. The factory operators for Single is more or less similar with observables restricted to a single emission. The only noticeable difference is the observer definition

public interface SingleObserver<T> {

    void onSubscribe(@NonNull Disposable d);

    void onSuccess(@NonNull T t);

    void onError(@NonNull Throwable e);
}

 

Like Observable there are no more onNext() and onComplete().

Example

Single so=Single.create(new SingleOnSubscribe<String>() {

            @Override
            public void subscribe(SingleEmitter<String> se) throws Exception {
              
                se.onSuccess("Success ");
                //se.onError(new Throwable("Exception"));
            }
        });
        so.subscribe(s->System.out.println(s));

 

While compile and run this will retrun the result as

Success 

if we need to perform a one time network request, we can create it using Single and users of this observable does not need to look at the implementation details to know what to expect from this observable

Example 2:

  Single<String> testSingle = Single.just("Single Observable");

      //Create an observer
      Disposable disposable = testSingle
         .delay(2, TimeUnit.SECONDS, Schedulers.io())
         .subscribeWith(
         new DisposableSingleObserver<String>() {

         @Override
         public void onError(Throwable e) { 
            e.printStackTrace();
         }

         @Override
         public void onSuccess(String value) {
            System.out.println(value);
         }
      }); 
      Thread.sleep(3000);
      //start observing
      disposable.dispose();

 

This will return output after 2 seconds

Single Observable