LifecycleObserever with Activities in Android
LifecycleObserever is Observer is one of the Jetpack Architecture components and is an interface that observes and performs the specified task depending upon the Lifecycle owner’s Lifecycle changes. For example, MainActivity has its own lifecycle and itself is Lifecycle owner and we can implement the LifecycleObserever interface and attach this observer to MainActivity so that certain operations can be performed as the lifecycle of the MainActivity changes. In this article, it’s been demonstrated how the LifecycleObserever performs the tasks as Lifecycle owner’s lifecycle changes. Have a look at the following video to get an overview of the discussion.
Note: This discussion is implemented using the Kotlin language.
Steps to implement the LifecycleObserever for the Android Application
Step 1: Create an empty activity project
Create an empty activity Android studio project and select Kotlin as the programming language. Refer Android | How to Create/Start a New Project in Android Studio?
Step 2: Adding the required dependencies
Add the following dependencies, to the app-level Gradle file. The dependencies are of the Lifecycle
// Lifecycles only (without ViewModel or LiveData)
// Annotation processor
Note: The version may differ in future.
And also enable the kapt plugin inside the plugins under the app-level gradle file.
If unable to get how to add dependencies have look at the following images.
Step 3: Working with acitivity_main.xml file
The main layout of the application is the activity_main.xml file contains only one TextView. To implement the UI invoke the following code inside the activity_main.xml file.
Step 4: Create a class that implements LifecycleObserver
Create a class MainActivityObserver.kt which implements the LifecycleObserver interface which contains the functions to perform the assigned tasks, as and when the owner’s lifecycle changes. In this case, the owner is MainActivity.kt, which has its own lifecycle. through the following class, the changes in the lifecycle of MainActivity are observed. Invoke the following code inside the MainActivityObserver.kt file.
Step 5: Attaching the MainActivityObserver to the MainActivity.kt file
Now there is a need to inform the activity by attaching the observer MainActivityObserver so that the desired tasks can be performed as the state of the activity changes. Invoke the following code inside the MainActivity.kt file.
Here the output is being shown in the logcat as there is an info logging statement inside the observer class.