Lifecycle Aware Components


Lifecycle is the biggest developer pain point. Lifecycle is hard. Lifecycle aware observable things that can do something base on the lifecycle. Your application must respect components lifecycles. Not doing so may trigger memory leaks or even application crashes.

Imagine we have an activity that shows the device location on the screen.

What if myLocationManager.addLocationListener() will be called after myLocationManager.removeLocationListenrer() called, basically keeping the connection forever.

Lifecycle aware component


New lifecycle-aware components provide constructs to tie core components(activity, fragment) of your applications to lifecycle events, removing explicit dependency paths.It can take care of itself. You can just initialize it and forget about it.


Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.

Lifecycle Components


This is a thing with a lifecycle, it is your activity or your fragment or maybe you have your own UI framework.There as a lifecycle Owner.


LifecycleObserver is the thing that cares about the Lifecycle.Like the LocationManager. It cares about the lifecycle, it wants to stop itself if the lifecycle is not active.

A class can monitor the component’s lifecycle status by adding annotations to its methods.

Now, we initialize MyLocationManager with our Lifecycle(MainActivity) on onCreate and stop worrying about it afterwards. This allows MyLocationManager class to be self sufficient, meaning that it can do its own cleanup when necessary.

Passes the LifecycleOwner as the first argument.

Adding Lifecycle to your Project

Architecture Components are available from Google’s Maven repository. To use them, follow these steps:

Add the Google Maven repository

To add it to your project, open the build.gradle file for your project and add the highlighted line as shown below:

Add Architecture Components

Open the build.gradle file for your app or module and add the artifacts that you need as dependencies:

Order of LifecycleObserver

if observer1 is added before observer2, then ON_CREATE is sent first to observer1, then to observer2 (same happens for ON_START and ON_RESUME), but ON_PAUSE event is sent first to observer2 and only then to observer1 (same for ON_STOP and ON_DESTROY).


Download this project from GitHub.

Related Post

Guide to Android Architecture Components


Room Persistence Library


Fragment Tricks

ConstraintLayout 1.1.x


Leave a Reply

Your email address will not be published. Required fields are marked *