RxJava Tutorial on RxJava Single Observable

the single class represents the single value response. single observable can only emit either a single successful value or an error. it does not emit oncomplete event.

class declaration

following is the declaration for io.reactivex.single<t> class −

public abstract class single<t>
   extends object
      implements singlesource<t>

protocol

following is the sequential protocol that single observable operates −

onsubscribe (onsuccess | onerror)?

single example

create the following java program using any editor of your choice in, say, c:\> rxjava.

observabletester.java

import java.util.concurrent.timeunit;

import io.reactivex.single;
import io.reactivex.disposables.disposable;
import io.reactivex.observers.disposablesingleobserver;
import io.reactivex.schedulers.schedulers;

public class observabletester  {
   public static void main(string[] args)  throws interruptedexception {
      //create the observable
      single<string> testsingle = single.just("hello world");

      //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();
   }
}

verify the result

compile the class using javac compiler as follows −

c:\rxjava>javac observabletester.java

now run the observabletester as follows −

c:\rxjava>java observabletester

it should produce the following output −

hello world