Observable error and empty method

In this post under RxJava, I will introduce you to Observable class’s two static methods “error” and “empty” methods.

The error method creates an Observable instance that will send the error thrown to the Observer/Subscriber.

The empty method creates as Observable instance that will not send any item, it just generate completion event to the Observer/Subscriber.

Below is an example

Example


1  import io.reactivex.rxjava3.core.Observable;
2  
3  public class Example5 {
4      public static void main(String[] args) {
5          Observable<NullPointerException> observable1 = Observable.error(new NullPointerException("Hello"));
6          observable1.subscribe(t -> System.out.println("Observable1 OnNext: " + t.toString()), t -> System.out.println("Observable1 OnError: " + t.getMessage()));
7          
8          Observable<Object> observable2 = Observable.empty();
9          observable2.subscribe(t -> System.out.println("Observable2 OnNext"),
10                  t -> System.out.println("Observable2 OnError"),
11                  () -> System.out.println("Observable2 OnComplete"));
12     }
13 }

In the above code, at line 5, we create an Observable instance that will throw an NullPointerException with the error message “Hello”. The static “error” method will take the exception instance as an argument.

Till now in previous posts, we used subscribe method that takes one callback function, which is called when onNext event is generated. In this code, at line 6, we use a overloaded version of subscribe method that takes two callback functions. First one is called when onNext event is generated and second one is called when onError event is generated. In this code, we throw the exception so onError event is generated and second callback function is executed.

At line 8, we create an Observable instance that will generate completion event. At line 9, we use another overloaded version of subscribe method that takes three callback functions. First one is called when onNext event is generated, second one is called when onError event is generated, and the third one when onCompletion event is generated. In this code, onCompletion event is generated and as a result third callback function is executed.

Below is the output

Output

Observable1 OnError: Hello
Observable2 OnComplete

Leave a Reply