I'm using ViewModel from Android Architecture Components in my app. In the ViewModel, I'm using RxJava2 subscription and I keep Disposable
object after I subscribe. Before, when I did this in Activity
, I was used to dispose the Disposable
in onDestroy()
- to avoid memory leaks:
@Override
protected void onDestroy() {
disposable.dispose();
super.onDestroy();
}
When and how should I dispose it in ViewModel
? Do I actually need to do that?
The CompositeDisposable class represents a container which can hold multiple disposable and offers O(1) complexity of adding and removing disposables.
RxJava 2 introduced the concept of Disposables . Disposables are streams/links/connections between Observer and Observable . They're meant to give power to the Observers to control Observables . In most cases, the Observer is a UI element, ie; Fragment , Activity , or a corresponding viewmodel of those elements.
A Disposable is a stream or a link between an Observable and an Observer . A quick check of the documentation shows that it has two main methods, dispose() and isDisposed() . The former disposes of the link, while the latter checks if the link has been disposed.
observable. onComplete() will complete your stream and so fire this event to all subscribers listening for onComplete , you don't need to dispose stream after onComplete (this is done automatically). disposable. dispose() will stop stream and no complete event will be fired.
with onCleared method
@Override
protected void onCleared () {
disposable.dispose();
super.onCleared ();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With