Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM - handling Disposable-s in ViewModel with RxJava and Room

I try to apply the MVVM pattern in my Android activity (I'm an Android noob).

I use Room with RxJava 2, e.g. this is a signature of a method in my repository:

public Single<MissionTask> getMissionTaskByID(long id) {..}

In my ViewModel class I have a reference to the repository and code like this:

private void doSomethingOnUserEvent() {
    ...
      missionTaskRepository.getMissionTaskByID(firstID).
          observeOn(AndroidSchedulers.mainThread()).
          subscribeOn(Schedulers.io()).
          subscribe(missionTask ->
              {
                // do some work and update live data
              },
              t -> {
                // handle error
              });
    ...
  }

So far so good, everything seems to work fine on the surface. Now - subscribe returns a Disposable.

My questions are:

  1. How should I handle the disposable (e.g. I can put it in a composite disposable and dispose the composite when the model is cleared)?
  2. What will happen if I do not dispose it? Leak? Why?

In some of the examples I've gone through there is no handling of the Disposable.

Update: I've seen the usage of composite disposable in android-architecture-components.

Thanks.

like image 525
Lachezar Balev Avatar asked May 04 '18 10:05

Lachezar Balev


1 Answers

Just clear your disposable/composite disposible in onCleared, this is enough

protected override onCleared(){
    if( diposable != null )
        disposable.dispose()
}
like image 128
Samuel Eminet Avatar answered Nov 09 '22 09:11

Samuel Eminet