Lifecycle-Aware Components in Android
Nov 1 2022 · Kotlin 1.6, Android 12, Android Studio Chipmunk 2021.2.1
Part 1: Lifecycle-Aware Components in Android
02. Understand Lifecycle-Aware Components
So let’s start exploring concepts with a very simple question. What exactly is meant by a lifecycle-aware component?
And, what problem does it solve in our application? Why should we use it?
Well, we all know what exactly is a
Activity and a
Fragment. We also know - they both contain lifecycle methods which are used to perform certain actions based on their states.
For example, in Activity’s onStart method, we can register a few components and use those components when the
Activity is in running state. At the same time, we also need to unregister those components in Activity’s
This sounds really simple, isn’t it? But in production level apps where you could have multiple components to register and unregister, it is quite possible you forget to unregister a few components within this
onStop method. Which could obviously lead to bugs, memory leaks, and even make your application to crash.
Well, the same problem is applicable for fragments as well.
Moreover, adding too much code within these lifecycle methods could make your code messy, error-prone, and difficult to maintain in the long run.
In fact, we should only keep UI related code within our
Fragment. Any other code other than that of UI should be kept out of these two classes.
So what is the solution for this? How can we ensure our code is organised and maintenable at the same time? So here comes lifecycle-aware components to the rescue.
To help us keep our code organised, we can create a separate class known as lifecycle-aware component. Well, this lifecycle-aware component is nothing but a simple class.
The role of this class is to react to the lifecycle changes taking place within this Activity and accordingly execute the code. So basically we can extract lifecycle related code from these methods and put them in this class and therefore, keep our Activity code clean and simple.
And since, this component is aware of the lifecycle of Activity in this case, that’s the reason it is known as ‘lifecycle-aware component’.
And for this Fragment as well, we can create its own Lifecycle-aware component, extract the code from these lifecycle-methods and put them within this component, which will of course keep the code well organised.
Okay, so now that we know what is a lifecycle-aware component, let’s start creating our very first lifecycle-aware component in the next episode.