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

06. Use Lifecycle States

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Explore Lifecycle Events Emitted by the LifecycleOwner Next episode: 07. Use ProcessLifecycleOwner

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 06. Use Lifecycle States

Ok, so let’s talk about this enum State.

Well, there are 5 possible values of State in which the lifecycle of an Activity or a Fragment or in short you say the lifecycle owner, can exist. They are INITIALIZED, CREATED, STARTED, RESUMED, and DESTROYED.

Now, using these values you can make sure your code is getting executed only when the lifecycle reaches a particular state. So let me throw some light on it.

Previously we discussed the Lifecycle events. When and how they are dispatched. Let’s talk about states now. Where does they fit in our Activity and Fragment lifecycle.

In case of Activity, before the onCreate method is executed, the lifecycle of an Activity is in INITIALIZED state. Once onCreate execution is over then comes the CREATED state. After onStart comes the STARTED state. After onResume comes the RESUMED state. Now, when onPause is about to get executed. Just before this method execution, Activity enters into the STARTED state again. Then right before the execution of onStop comes the CREATED state.

Now, please note that these two are the same lifecycle state which we saw in the constructive phase of Activity’s lifecycle over here. Lastly, before onDestroy method is executed, comes the DESTROYED state.

So now, please note that similar to these events, the states are reached only after the lifecycle methods execution is completed.

But here, at the bottom, we can see the opposite. Such as these states are reached just before the execution of callback methods. Fine? So this was about Activity lifecycle states.

Let’s take a look at Fragment states. Here as well, we can see the similar pattern but of course with a slight difference. Before onCreate, the state in which the fragment exist is the INITIALIZED. After onCreate execution is over, the state becomes CREATED. Now, this CREATED state is continued until the onStart method has finished its execution. Which means if you try to check the lifecycle state within these three methods, you will get state as CREATED. So please note this.

Then after onStart comes STARTED state. Then comes RESUMED state after onResume method. Then soon when the Fragment is about to call onPause method, the state changes to STARTED. Then before onStop, state becomes CREATED. So here as well, this CREATED state is continued till the onDestroyView method. Then lastly, before onDestroy comes the DESTROYED lifecycle state.

So in future, if you want to use events and states in your project, you can refer to this slide. Trust me, this slide will definitely act as your saviour if you want to refer to events and states of Activity and Fragment.

Now, the biggest question arises, how can we access these states and how can we use them in our current project or any other project.

Well, we need to get reference to the State object and to do that we can use the lifecycle object and use currentState property. This will return the State object.

Now, the State contains a method known as isAtLeast(). So using this method, you can know in which state your Activity or Fragment is currently in. And accordingly using the if condition you can execute your desired code. Ok, so let’s see some code in action for more clarity.

So here in our NetworkMonitor my intention is to make sure that this code is executed only when the Activity is in STARTED state or atleast in STARTED state.

And to do that, we need to use the lifecycle object. But the NetworkMonitor class has no direct access to the Lifecycle object. Right? Because the Lifecycle object can only be found within a LifecycleOwner class, which in our case is the MainActivity.

So within our MainActivity, within our onCreate function. Here, where we are initializing our NetworkMonitor, we can pass lifecycle object as a parameter.

  networkMonitor = NetworkMonitor(this, lifecycle)

And in NetworkMonitor let’s update its constructor to receive that parameter. Perfect!

    class NetworkMonitor constructor(
        private val context: Context,
        private val lifecycle: Lifecycle
    ): DefaultLifecycleObserver {

    }

Perfect! Now, within our registerNetworkCallback() method.

We can write a if condition and wrap these two lines of code, within this. And, we can use lifecycle, getCurrentState, use isAtLeast method and use the state of STARTED.

    if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
      initCoroutine()
      initNetworkMonitoring()
    }

So with this condition, NetworkMonitor will only start monitoring the network connection when the MainActivity is at least in the STARTED state.

So yes, in this way you can make effective use of lifecycle states. I am sure you can do wonders in your production level application with this feature. That’s all for this episode.