Architecture Components: Lifecycle-Aware and Use cases

Nam Bui Van
4 min readSep 30, 2020

--

Currently, most Android Developers have already known and regularly use Architecture Components in their projects.

We are no stranger to LiveData, ViewModel, Room and Worker.
What about “Lifecycle-Aware”? It are easy to understand, but how often do we use it?

In this blog, we are going to learn more about use cases for Lifecycle-Aware component. 🔥

Photo by Blake Connally on Unsplash

Intro

During develop process, we have encountered many cases, we want to perform some functions of class A get from Android APIs (such as Context getters and getSystemService()) in lifecycle methods of some components like activity or fragment.

Usually, we will have to initialize it in onCreate(), registerStateChange in onResume(), unRegisterCallBack in onStop() and release all in onDestroy()

In fact, we implement a lot of functions like A in activity/fragment.
Noticeable, the code above is a poor organization of the code and to the proliferation of errors

A simple solution, we can define a class for a function to handle all that is related to it.

And the activity/fragment:

Above solution be used a lot.
However, the functions of class A always dependent on lifecycle of activity/fragment, and we must remember destroy/release/unRegister A if need in onStop() or onDestroy() of activity/fragment, not doing so may trigger memory leaks.

If we have many class like class A → We will have too many calls in lifecycle methods → difficult to maintain.

Recommend solution in this case is use “Lifecycle-Aware” . By using it, you can move the code of A in the lifecycle methods into the components themselves. So, we can adjust behavior of A based on the current lifecycle state of activity/fragment in itself. From there we can easily control, debug, maintain and code is also cleaner.

How to use Lifecycle-Aware? 👀

According to Google:

“Lifecycle-Aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments. These components help you produce better-organized, and often lighter-weight code, that is easier to maintain.”

Lifecycle-Aware Components

To better understand and how to implement it, let’s look at the examples below. 👇

We will build an application demo check status of network realtime in device (connected or disconnected) and notify for user when app in foreground.
In fact this is necessary for projects related to the internet, they will check the status of the network to perform some functions as well as display the user’s network status.

Let’s code!!!! 👊

Firstly, create a project Kotlin by Android Studio like below sample

Sample Lifecycle-Aware

We will add android.permission.ACCESS_NETWORK_STATE in AndroidManifest.xml to registerDefaultNetworkCallback() from ConnectivityManager .

Add lib to use Snackbar show status network for user.

implementation "com.google.android.material:material:1.3.0-alpha02"

NetworkUtils.kt define extensions check network connected or not.

Next, we will use Lifecycle and LifecycleObserver. Let’s find out a little bit!

“Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observer this state.”

We use Event enum or State enum in Lifecycle class to tracking lifecycle state of related component.

  • State: current stable state of component tracked
  • Event: map to the lifecycle methods of Activity/Fragment
Event and States in Lifecycle (source by Google)

To a class can automatic tracking lifecycle state, we implement LifecycleObserver, then use addObserver() method of the Lifecycle class and passing an instance of our observer

NetworkConnectLifecycle.kt class will implement LifecycleObserver , we pass Context and Lifecycle into constructor.

Use lifecycle.addObserver(this) to tracking lifecycle state, and onDestroy() we must removeObserver (uselifecycle.removeObserver(this)).

networkChange: ((Boolean) -> Unit) is function will be called when network state change.

In onResume() call mConnectActivityManager.registerDefaultNetworkCallback(this) to register network state change in foreground,
and we will unregister network change in background by call mConnectActivityManager.unregisterNetworkCallback(this) in onStop()

→ All are automatically listened and executed in NetworkConnectLifecycle.kt, which we have often done in activity or fragment for a while

And in MainActivity.kt:

Create instance of NetworkConnectLifecycle and pass fun handleNetworkChange(connected: Boolean) handle update UI when network state change.

Result check connect status

Run code and here is the result:

Check full code in:

Conclude

Lifecycle-Aware can help us manage class depends on lifecycle of activity or fragment in a great way!!!

We usually Lifecycle-Aware when we want to manage lifecycles in a variety of cases. Especially in the cases the application is at foreground state or at background state

Example:

  • Register, unRegister and observer Broadcast Receiver, ContentProvider, AccountManager update…
  • Init, play, pause, stop and release mediaPlayer, mediaRecorder
  • Handle stop and start video buffering (like play video with exoPlayer…)
  • Listener state network connectivity change.

Hopefully this article will help you to understand more about how to use it in real situations.

Let me know your thoughts on this article.

Thanks!!! Happy Coding! 😇

--

--

Nam Bui Van

I ‘m a Mobile Developer. #AndroidDeveloper #Kotlin #Flutter