The following is the first few sections of a chapter from Android's Architecture Components, plus headings for the remaining major sections, to give you an idea about the content of the chapter.


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:

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.

Bridging RxJava and LiveData

The preview of this section was last seen in the Bermuda Triangle.

The Uber Solution: AutoDispose

The preview of this section was last seen in the Bermuda Triangle.

The Semi-Deprecated Solution: RxLifecycle

The preview of this section is [REDACTED].