RxJava

Do you want to make sure that your Rx Java Disposables are disposed from the viewModel when they are no longer needed?

Android RxJava Tips Tricks

Pure Rx Java solution

  1. Create CompositeDisposable as field
  2. Register all your Disposables via its add method.
  3. When you don’t need to receive more updates call clear:
public class RxLifecycleViewModel extends ViewModel {
    private final CompositeDisposable disposables = new CompositeDisposable();

    public void onAttach(final ViewInterface view) {
        disposables.add(Observable.interval(1, TimeUnit.SECONDS)
                .subscribe(aLong -> {
                        view.updateText(aLong);
                }));
    }

    public void onDetach() {
        disposables.clear();
    }
}

 

This does work, but there are small issues:

  • Wrapping all your Rx calls introduces unpleasant nesting.
  • You need to manually inform viewModel when it has to attach/detach from updates.Fortunately we can do better with Kotlin and SecretSauce:

Kotlin with SecretSauceKt solution:

    1. Make your ViewModel extend AttachableViewModelRx from SecretSauce.
  • Register your Disposable to be detached disposeOnDetach extension function.
  • Profit
class RxLifecycleViewModel : AttachableViewModelRx<Any>() {
    override fun onAttach(view: ViewInterface) {
        Observable.interval(1, TimeUnit.SECONDS)
                .subscribe { view.updateText(it) }
                .disposeOnDetach()
        super.onAttach(view)
    }
}

Full sample at Github