CompositeDisposable

October 15, 2018

Let’s imagine that you have multiple subscriptions that need to be disposed. In such cases a container would be helpful where you could store all these subscriptions and then dispose all of them at once. Such container is the CompositeDisposable.
Internally it holds a collection of Disposables and it guarantees O(1) for addition and removal to this collection via methods such as add(), addAll(), delete() and remove().

import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Observable<Long> interval = Observable.interval(1, TimeUnit.SECONDS);

        Disposable disposable1 = interval.subscribe(s -> System.out.println("Observer1: " + s + " second(s) passed!"));
        Disposable disposable2 = interval.subscribe(s -> System.out.println("Observer2: " + s + " second(s) passed!"));

        CompositeDisposable compositeDisposable = new CompositeDisposable();
        compositeDisposable.addAll(disposable1, disposable2);

        Thread.sleep(5500);

        System.out.println("Disposing now!");
        compositeDisposable.dispose();

        Thread.sleep(2500);
    }
}

One thing worth noting is that delete() removes the Disposable if it is part of the CompositeDisposable, but does not call dispose() for the removed Disposable.
On the other hand, remove() calls the dispose() first and then removes the Disposable from the CompositeDisposable.
Another important thing is that CompositeDisposable is not reusable after the dispose() method was called on it.

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami