11

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.

Lachezar Balev
  • 11,498
  • 9
  • 49
  • 72
  • Use `onCleared` ...example of doing this in https://github.com/joreilly/galway-bus-android/blob/master/base/src/main/java/com/surrus/galwaybus/ui/viewmodel/BusRoutesViewModel.kt – John O'Reilly May 04 '18 at 10:45
  • Look it might help : https://medium.com/@saquib3705/consuming-rest-api-using-retrofit-library-with-the-help-of-mvvm-dagger-livedata-and-rxjava2-in-67aebefe031d – Mohd Saquib May 07 '18 at 05:40

1 Answers1

7

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

protected override onCleared(){
    if( diposable != null )
        disposable.dispose()
}
Samuel Eminet
  • 4,647
  • 2
  • 18
  • 32
  • I guessed that and saw how to use composite disposable. But why should I do that with Room? :-) – Lachezar Balev May 04 '18 at 10:49
  • why you shouldn't? you should always dispose ongoing action when your viewmodel is destroyed, with a Single this is indeed not as a big deal than an Observable since it may dispose itself eventually but could be after onCleard though – Samuel Eminet May 04 '18 at 10:58
  • Maybe it would be a best practice to use subscribe with SingleObserver in a case when handling Single? – Lachezar Balev May 04 '18 at 11:13