Lifecycle-Aware Components Using Android Jetpack

Learn about lifecycle-aware components including what they are, how they work, how to implement your own components and how to test them. By Rodrigo Guerrero.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

LiveData: A Lifecycle-Aware Component

So far in this tutorial, you’ve seen how to create your own lifecycle-aware components. But are there any lifecycle-aware components already available in Android? The answer is yes, and maybe the most famous of them is LiveData.

The concept behind LiveData is simple. It’s an observable data holder class, which means it can contain data and it will notify its observers when that data changes. However, the nice thing about LiveData is that it’s lifecycle-aware, meaning that it only updates its observers when the lifecycle is in an active state.

An observer is in active state if its lifecycle is in the STARTED or RESUMED state. If the lifecycle is in another state, then LiveData won’t notify its observers of any changes.

Creating and Assigning LiveData Variables

Open MainViewModel.kt from the viewmodels package. Inside, add the following variables:

private val _loadingState = MutableLiveData<UiLoadingState>()
val loadingState: LiveData<UiLoadingState>
  get() {
    return _loadingState
  }

loadingState is a LiveData that can have two possible values: Loading and NotLoading. This value will tell the view if it needs to display or hide the progress bar.

Whenever a LiveData variable gets a new value, it notifies its observers about the change. To achieve this, you use its value property.

Modify getRandomRecipe() as follows:

fun getRandomRecipe() {
  _loadingState.value = UiLoadingState.Loading
  viewModelScope.launch {
    recipeRepository.getRandomRecipe().collect { result ->
      _loadingState.value = UiLoadingState.NotLoading
      _recipeState.value = result
    }
  }
}

Now, updating value will notify all the observers of the updates to _loadingState.

Observing LiveData Changes

Open MainActivity.kt and add the following in its onCreate():

viewModel.loadingState.observe(this, Observer { uiLoadingState ->
  handleLoadingState(uiLoadingState)
})

With this code, MainActivity will start observing updates on viewModel.loadingState. As you can see, the first parameter in observe() is this, which is the current instance of MainActivity. Look at the signature of observe() and you’ll see that its first parameter is a LifecycleOwner. This means that LiveData‘s observers will react depending on the state of the activity’s lifecycle. Control– or Command-click observe to inspect the method signature.

Look within observe():

if (owner.getLifecycle().getCurrentState() == DESTROYED) {
  // ignore
  return;
}

Here, you see that if LifecycleOwner is DESTROYED and a new value is set to the LiveData variable, then the observer will do nothing.

However, if the LifecycleOwner becomes active again, the observer will receive the last available value automatically.

Build and run. The app will show a progress bar while loading the data. It will hide the progress bar after the data loads.

Congratulations! You’ve successfully migrated an app to use lifecycle-aware components.

Where to Go From Here?

You can download the final project by using the Download Materials button at the top or bottom of the tutorial.

Jetpack offers other libraries of Android architecture components. To get to know more of them, check out Android Jetpack Architecture Components: Getting Started.

Additionally, to learn more about testing architecture components, check out Testing Android Architecture Components.

To dig deeper into LiveData, read LiveData Tutorial for Android: Deep Dive.

For more information about architecture components, head to Architecture Components: Official Documentation.

I hope you enjoyed this tutorial on lifecycle-aware components. If you have any questions or comments, please join the forum discussion below.