dispose vs clear CompositeDisposable RxJava

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
dispose vs clear CompositeDisposable RxJava

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about the dispose method and the clear method of CompositeDisposable that is present in the RxJava.

I have realized that many developers are having confusion about when to use the dispose() method and when to use the clear() method of CompositeDisposable. So, I will clarify it for you.

For that, let's take an example.

private val disposables = CompositeDisposable()

private fun sampleObservable(): Observable<String> {
    return Observable.defer {
        // Do some long running operation
        SystemClock.sleep(2000)
        return@defer Observable.just("one", "two", "three", "four", "five")
    }
}

// adding an Observable to the disposable
disposables.add(
    sampleObservable()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeWith(object : DisposableObserver<String>() {

            override fun onNext(value: String) {

            }

            override fun onError(e: Throwable) {

            }

            override fun onComplete() {

            }
        })
)

Now, we have two methods available with the CompositeDisposable:

  • clear() - When we use the clear() method, it will clear all the disposables but can accept a new disposable.
disposables.clear()
  • dispose() - When we use the dispose() method, it will clear all the disposables and set isDisposed = true, so it will not accept any new disposable.
disposables.dispose()

This must have given you clarity. Now, you can decide which one to use when based on your requirement.

This was all about the dispose method and the clear method of CompositeDisposable that is present in the RxJava.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.