RxJava and Lifecycles
RxJava is cool, albeit confusing. But beyond that, it is a pure Java library. RxJava knows nothing about Android-specific concepts, as it is designed to be used on all sorts of Java projects.
Android developers using RxJava invariably also add RxAndroid, which gives us access to a Scheduler
that knows about the Android main application thread. However, RxAndroid does not have anything that deals with activity or fragment lifecycles, leaving that up to you. With Android lifecycles, we want to create things as activities and fragments start up and clean up those things as the activities and fragments go away. In the case of RxJava, if we subscribe to some Observable
, it would be nice to get rid of that subscription at an appropriate point.
In this chapter, we will explore a few options — including one from the Architecture Components — for dealing with lifecycles with RxJava.
The Classic Approach
The default way of handling this is the approach used in the chapter on RxJava and Room:
- Hold onto the
Disposable
that you get back from subscribing to an observable - Clean up that
Disposable
in a suitable lifecycle method, such asonDestroy()
, via a call todispose()
If you have several subscriptions to track, CompositeDisposable
lets you track all of them in one spot. CompositeDisposable
has add()
and addAll()
methods to add subscriptions to it. And, as the name suggests, CompositeDisposable
implements the composite pattern, and so CompositeDisposable
itself is a Disposable
. Calling dispose()
on the CompositeDisposable
triggers calls to dispose()
on all of the Disposable
objects you added to the composite.
This works, but it does require you to remember to clean these things up, and it is easy to forget.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.