Updated 30 April 2019
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.
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
1 2 3 |
implementation "android.arch.lifecycle:runtime:1.1.1" implementation "android.arch.lifecycle:extensions:1.1.1" annotationProcessor "android.arch.lifecycle:compiler:1.1.1" |
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
1 2 3 4 5 |
override fun onCreate(savedInstanceState: Bundle?) { // TODO getLifecycle().addObserver(MainActivityObserver()) // TODO } |
To attach event with the method all we have to do just add annotation with the event.
1 2 3 4 |
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { // TODO } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class MainActivityObserver() : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreateObserver() { // Perform any action onCreate } @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStartObserver() { // Perform any action onStart } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE,Lifecycle.Event.ON_STOP) fun onPauseObserver() { // Perform any action onPause and onStop } } |
Hope this blog helps you to understand the lifecycle observer feature and write lean code for application lifecycle event.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.