Lifecycles and Owners

Programmers, in any environment, often encounter one or more topics that inspire the five stages of grief. It might be related to threads, to security, to UI implementation (e.g., how to deal with resizeable windows).

Android developers experience this sort of grief on all those topics.

Another one that triggers this sort of grief is the concept of lifecycles. On the surface, the concept seems unremarkable: objects are in use for a time and then become discarded, and along the way we receive callbacks regarding their state. However, dealing with the ramifications of those lifecycles — such as handling configuration changes, like screen rotation — vex even seasoned Android developers.

Part of the Architecture Components is a series of classes designed to help you deal with lifecycles in a more consistent fashion.

A Tale of Terminology

The Architecture Components have very specific definitions for certain terms, and these definitions affect the classes that we wind up using.

Lifecycle

A lifecycle is a series of states that an object can be in. Hence, a trivial lifecycle simply has “alive” and “dead” or similar states.

The eponymous Lifecycle class, however, models a specific lifecycle, that of activities and fragments.

Lifecycle Owner

A lifecycle owner is simply something that goes through a lifecycle. If the lifecycle is the state, the lifecycle owner is what has the trigger events for navigating through the state machine.

A LifecycleOwner is a Java interface, with a getLifecycle() method, that returns the Lifecycle for a given owner. As we will see, various classes already implement LifecycleOwner, and adding it to something else is not especially difficult.

Lifecycle Observers

A lifecycle observer is something that is notified about the change in state of some lifecycle. It finds out about those trigger events and the movement of the lifecycle from state to state.

There are two ways to do this, via annotations and via DefaultLifecycleObserver, as we will explore later in this chapter.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.