Android Lifecycle-Aware Components

The earlier chapter, Android App and Activity Lifecycles, described the use of lifecycle methods to track lifecycle state changes within a UI controller such as an activity or fragment. One of the main problems with these methods is that they place the burden of handling lifecycle changes onto the UI controller. On the surface, this might seem like the logical approach since the UI controller is, after all, the object going through the state change. However, the fact is that the code typically impacted by the state change invariably resides in other classes within the app. This led to complex code appearing in the UI controller that needed to manage and manipulate other objects in response to changes in the lifecycle state. This scenario is best avoided when following the Android architectural guidelines.

A much cleaner and more logical approach would be for the objects within an app to be able to observe the lifecycle state of other objects and to be responsible for taking any necessary actions in response to the changes. For example, the class responsible for tracking a user’s location could observe the lifecycle state of a UI controller and suspend location updates when the controller enters a paused state. Tracking would then be restarted when the controller enters the resumed state. This is made possible by the classes and interfaces provided by the Lifecycle package bundled with the Android architecture components.

This chapter will introduce the terminology and key components that enable lifecycle awareness to be built into Android apps.

Lifecycle Awareness

An object is said to be lifecycle-aware if it can detect and respond to changes in the lifecycle state of other objects within an app. Some Android components, LiveData being a prime example, are already lifecycle-aware. Configuring any class to be lifecycle-aware is also possible by implementing the LifecycleObserver interface within the class.

Lifecycle Owners

Lifecycle-aware components can only observe the status of objects that are lifecycle owners. Lifecycle owners implement the LifecycleOwner interface and are assigned a companion Lifecycle object responsible for storing the current state of the component and providing state information to lifecycle observers. Most standard Android Framework components (such as activity and fragment classes) are lifecycle owners. Custom classes may also be configured as lifecycle owners using the LifecycleRegistry class and implementing the LifecycleObserver interface. For example:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook  

 

class SampleOwner: LifecycleOwner(override val lifecycle: Lifecycle) {
 
    private val lifecycleRegistry: LifecycleRegistry
 
    init {
        lifecycleRegistry = LifecycleRegistry(this)
        lifecycle.addObserver(DemoObserver())
    }
}Code language: Kotlin (kotlin)

Unless the lifecycle owner is a subclass of another lifecycle-aware component, the class will need to trigger lifecycle state changes via calls to methods of the LifecycleRegistry class. The markState() method can be used to trigger a lifecycle state change passing through the new state value:

fun resuming() {
    lifecycleRegistry.markState(Lifecycle.State.RESUMED)
}Code language: Kotlin (kotlin)

The above call will also result in a call to the corresponding event handler. Alternatively, the LifecycleRegistry handleLifecycleEvent() method may be called and passed the lifecycle event to be triggered (which will also result in the lifecycle state changing). For example:

lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)Code language: Kotlin (kotlin)

Lifecycle Observers

To observe the state of a lifecycle owner, a lifecycle-aware component must implement the DefaultLifecycleObserver interface and override methods for any lifecycle change events it needs to observe.

class DemoObserver: DefaultLifecycleObserver {
    // Lifecycle event methods go here
}Code language: Kotlin (kotlin)

An instance of this observer class is then created and added to the list of observers maintained by the Lifecycle object.

lifecycle.addObserver(DemoObserver())Code language: Kotlin (kotlin)

An observer may be removed from the Lifecycle object anytime if it no longer needs to track the lifecycle state. Figure 45-1 illustrates the relationship between the key elements that provide lifecycle awareness:

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook  

 

Figure 45-1

Lifecycle States and Events

When the status of a lifecycle owner changes, the assigned Lifecycle object will be updated with the new state. At any given time, a lifecycle owner will be in one of the following five states:

  • Lifecycle.State.INITIALIZED
  • Lifecycle.State.CREATED
  • Lifecycle.State.STARTED
  • Lifecycle.State.RESUMED
  • Lifecycle.State.DESTROYED

The Lifecycle object will trigger events on any observers added to the list as the component transitions through the different states. The following event methods are available to be overridden within the lifecycle observer: • onCreate()

  • onResume()
  • onPause()
  • onStop()
  • onStart()
  • onDestroy()

The following code, for example, overrides the DefaultLifecycleObserver onResume() method:

override fun onResume(owner: LifecycleOwner) {
    // Perform tasks in response to Resume status event
}Code language: Kotlin (kotlin)

The flowchart in Figure 45-2 illustrates the sequence of state changes for a lifecycle owner and the lifecycle events that will be triggered on observers between each state transition:

Figure 45-2

Summary

This chapter has introduced the basics of lifecycle awareness and the classes and interfaces of the Android Lifecycle package included with Android Jetpack. The package contains several classes and interfaces for creating lifecycle owners, observers, and lifecycle-aware components. A lifecycle owner has assigned to it a Lifecycle object that maintains a record of the owner’s state and a list of subscribed observers. When the owner’s state changes, the observer is notified via lifecycle event methods to respond to the change.

 

You are reading a sample chapter from an old edition of the Android Studio Essentials – Kotlin Edition book.

Purchase the fully updated Android Studio Ladybug Kotlin Edition of this publication in eBook or Print format.

The full book contains 100 chapters and over 878 pages of in-depth information.

Learn more.

Preview  Buy eBook  

 

The next chapter will create an Android Studio project that demonstrates how to work with and create lifecycle-aware components, including the creation of both lifecycle observers and owners and the handling of lifecycle state changes and events.