dispose vs clear CompositeDisposable RxJava
- Authors
- Name
- Amit Shekhar
- Published on
I am Amit Shekhar, 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.
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 theclear()
method, it will clear all thedisposables
but can accept a newdisposable
.
disposables.clear()
dispose()
- When we use thedispose()
method, it will clear all thedisposables
and setisDisposed = true
, so it will not accept any newdisposable
.
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
You can connect with me on: