Disposing an automatically created Observer

In this post, I will explain how to dispose an automatically created Observer.

In all my previous posts, when I provide the below code snippet, it was creating an Observer internally that will compose these lambda callback functions provided as arguments to the “subscribe” method.


    observable.subscribe(t -> System.out.println(t), t -> t.printStackTrace(), () -> System.out.println("Complete"));

In addition to creating an Observer automatically, it was also returning “Disposable” object.

The “Disposable” object can be used to sever the subscription between the Observer and Observable.

In the above snippet we are not storing the returned “Disposable” object to a variable.

If we have stored the returned “Disposable” object to a variable, we can later dispose the subscription by calling “dispose” method on the “Disposable” object, as shown in the below snippet


    Disposable disposable = observable.subscribe(t -> System.out.println(t), t -> t.printStackTrace(), () -> System.out.println("Complete"));
    disposable.dispose();

This disposable object is helpful to end the subscription to an never ending observable as is the case in the above example.

Below is the complete code for your reference.

Main Class


import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;

public class Example18 {
    public static void main(String[] args) throws Exception {
        Observable<Long> observable = Observable.interval(1000, TimeUnit.MILLISECONDS);
        Disposable disposable = observable.subscribe(t -> System.out.println(t), t -> t.printStackTrace(), () -> System.out.println("Complete"));
        Thread.sleep(5000);
        disposable.dispose();
    }
}

Leave a Reply