Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to dispose RxJava2 Disposable in ViewModel?

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?

like image 446
Micer Avatar asked Apr 01 '18 19:04

Micer


People also ask

What is composite disposable in Android?

The CompositeDisposable class represents a container which can hold multiple disposable and offers O(1) complexity of adding and removing disposables.

What is disposable in RxJava Android?

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.

What is the use of disposable in Android?

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.

How do you dispose of observables?

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.


1 Answers

with onCleared method

@Override
protected void onCleared () {
    disposable.dispose();
    super.onCleared ();
}
like image 65
Samuel Eminet Avatar answered Sep 18 '22 20:09

Samuel Eminet