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.rxjava3.core.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)?

Example - Creating a Single Observable Class to get Data

ObservableTester.java

package com.tutorialspoint; import io.reactivex.rxjava3.core.Single; public class ObservableTester { public static void main(String[] args) throws InterruptedException { Single.just("Hello world").subscribe(System.out::println); } }

Output

Compile and Run the code to verify the following output −

Hello World

Example - Usage of Single 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.Single; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.observers.DisposableSingleObserver; import io.reactivex.rxjava3.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(); } }

Output

Compile and Run the code to verify the following output −

Hello World
Advertisements