dispose vs clear CompositeDisposable RxJava

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

I am Amit Shekhar, Co-Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Join Outcome School and get high paying tech job: Outcome School

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

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.

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar
Co-Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.