Working with Android LifeCycle Observer Architecture Component

Updated 30 April 2019

Save

What is LifeCycle Observer in Android?

Lifecycle is an Abstract class in Android which attaches with Application lifecycle. It helps to manage the lifecycle event of the activity or fragment.  It helps to manage the state of the application event. We can also define multiple lifecycle events on the same method using annotated. We can manage the lifecycle event like onCreate, onStart and onStop in our custom observer class.

What is the Event in the lifecycle of Android Application?

An event is the lifecycle event that has been triggered by a lifecycle change (such as resuming an activity). In our classes, we can implement callbacks for each of these events so that we can handle lifecycle changes. The arch.lifecycle package provides an Annotation for us to use which means we can annotate the methods within our class which should be triggered upon certain lifecycle events.

Add a dependency in your build.gradle

In this example, we going to implement lifecycle observer in our MainActivity class. To implement Custom Lifecycle observer we are going used getLifecycle() method in onCreate() method which return Lifecycle instance of the activity and we will use an addObserver method where we have passed the object of our custom MainActivityObserver class

To attach event with the method all we have to do just add annotation with the event.

MainActivityObserver implement LifecylceObserver interface. We can also handle multiple lifecycle events within the same annotated method, this allows us to trigger a specific method based on multiple lifecycle events being triggered:

Hope this blog helps you to understand the lifecycle observer feature and write lean code for application lifecycle event.

author
. . .

Leave a Comment

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


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home