The Activity lifecycle vs. the world
A common problem people run into with Activities
are handling runtime configuration changes. This situation ought to sound familiar:
- The user initiates a network request in an
Activity
. - The user rotates the screen.
- The
Activity
is destroyed and recreated with a new configuration. - Your network request is lost because it only had references to the initial
Activity
.
The solution is quite simple: if the logic needs to live beyond the duration of the lifecycle, put it somewhere outside the lifecycle.
For example, your network request should deliver its results to some intermediary such as an in-memory cache. Then the Activity
can retrieve the results when complete.
People often confuse themselves by thinking a specific tool is the solution to the problem when it's actually just an implementation detail. "How does RxJava handle config changes?" is a question I've been asking many times, but to me the question makes little sense because RxJava has no explicit API for Android. It's just a library for handling streams of data.
You can certainly use RxJava in your solution. The reactive way to inform the Activity
of UI changes is to create an Observable<Data>
and subscribe. But that alone is not the solution to config changes; if your Observable<Data>
was contained in the Activity
you'd still have the same problem as before! The actual solution is in ensuring your Observable<Data>
lives somewhere outside of the lifecycle.
It's simpler (at least in my mind) to separate out the core solution from the tools used to implement it. The core solution is writing logic that lives beyond a single lifecycle. The way you do that is up to you.