Skip to main content

Lifecycle Aware Data and Configuration change handling with LiveData

LiveData is a data holder class of Google latest Architectural Component which can be observed and in case of any change in the data, it will notify the bound activity or fragment about the change. So what is the difference between normal observer and LiveData observer? and the answer to this question is that Livedata observer is the lifecycle aware class.

What does mean if we say Lifecycle aware class?

As you know any activity and fragment goes through several states, like an activity is created, started, paused, destroyed and resumed. So normal observer doesn't know about these state of the activity and fragment but Livedata knows. That's why we say LiveData is the lifecycle aware class.

The benefit Lifecycle aware class like Livedata?

The main benefit of Lifecycle aware class is that you don't have to worry lifecycle of bound activity and fragment changed. So we don't need to update the UI manually instead of that we can create the observer to update the UI with the latest data automatically if data has been changed.

  • We don't require manual lifecycle management.

  • LiveData object will remain for the whole lifecycle of the bound component.

  • There is no chance of memory leaks with LiveData. because it has auto cleanup functionality.

  • It will also minimize the chance of app crash due activity is stopped. Because it will only send the data when lifecycle component is active.

  • It will always keep up to date data to your UI. Becuase it will send the data as soon as your active will alive again if your activity is coming from back stack.

  • No more manual configuration change handling. It will send the latest data automatically if your activity is recreated due any reason like screen rotation.

Difference between LiveData and ViewModel and its use

LiveData is the class which can be observed and ViewModel is the class which can hold the data of the activity and fragment. In simple we can say ViewModel store the data and LiveData will keep eyes on those data. In case of any change immediately notify the bound activity and fragment. If you want to learn more about the ViewModel kindly refer our earlier tutorial about ViewModel.

Prerequisite of LiveData implementation

  • We need to add Google repository in project level build.gradle file.

  • Also, add the below dependency to your app level build.gradle component.

implementation "android.arch.lifecycle:extensions:1.0.0"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
testImplementation "android.arch.core:core-testing:1.0.0"

If you went through my earlier post about ViewModel.We have implemented the ViewModel to preserve the click count data. Here in this example for better understanding about the use of LiveData. We will continue the same pattern and implement the it along with ViewModel.

Description of the Demo app of LiveData and ViewModel

In the Last tutorial of the ViewModel, we increase the count of the click every time user click on the button and we set and data into the TextView and update the ViewModel data manually.
// Check if View Model have some value
// else initialize with initial setup
txtClickMe.setText("You Have Clicked " + clickMe + " Times");
btnClickMe.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
txtClickMe.setText("You Have Clicked " + clickMe + " Times");
//set the Click Count to ViewModel

So here, In this article, I am going to explain to you how we can use the LiveData and ViewModel together to update TextView automatically when data changed.

LiveData Arcticutre Digram of Example

For better understanding, we are not going to increase the count of "button click" instead of that we are going to implement a counter which increases the count every second.

So, first of all, we will create our ViewModel class as given below.

package com.nplix.livedataexample;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;

import java.util.Timer;
import java.util.TimerTask;

* Created by PK on 1/14/2018.

public class CounterViewModel extends ViewModel {

private MutableLiveData<Integer> counter=new MutableLiveData<>();

private static int ONE_SECOND=1000;
private static int InitCount=0;

public CounterViewModel(){
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
public MutableLiveData<Integer> getCounter() {
return counter;

Our main activity will look like as given below.

package com.nplix.livedataexample;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
CounterViewModel counterViewModel;
protected void onCreate(Bundle savedInstanceState) {
final TextView counterTextView=findViewById(;
//Declare the Counter Data Model
//Create the Observer for for Model
Observer<Integer> dataObserver=new Observer<Integer>() {
public void onChanged(@Nullable Integer integer) {
counterTextView.setText("Counter at :"+integer);
Log.d("LiveData Update:","Data has been updated, current value is"+integer);
//set the observer on LiveData


If you run the above demo example of LiveData and ViewModel. Then you can observe that if your activity is paused or screen rotation was done. Then observer will stop the sending the update to your UI. And Activity comes alive again it will stop the TextView with latest data.

LiveData Example Livedata and ViewModel Example

If you have look at the above screenshots of logs. When we paused our activity observer stop sending the update about the data. When activity comes alive again its send the latest data to UI.

LiveData provides two public methods for post and set the value of data. Below is the sample example of both method.

For set the data we can use the setData(value) method and for posting it we can use the postdata(value). We will come with some more example and scenarios of its use.

Download the Source Code of this app from GitHub.


  1. […] Further check out the next part of this tutoiral Lifecycle Aware Data and Configuration change handling with LiveData […]

  2. […] class. If you want to learn about the LiveData and ViewModel you can check out the article on LiveData and ViewModel which we published […]

  3. […]  Lifecycle Aware Data and Configuration change handling with LiveData  […]


Post a Comment

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit. What is Retrofit? If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps. Further, you can check the Retrofit Library here . So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website. Prerequisite for using the Retrofit for WordPress Android App Ther

How to Read and Write JSON data in Kotlin with GSON

Kotlin is now official language for Android development and it is well supported in Android Studio. So here in this tutorial, we are going to learn about how to read and write JSON data in Kotlin using GSON. If you would like to learn the java version of this tutorial check out the last tutorial " How to Read and Write JSON data using GSON ". Introduction In this tutorial, we will write two methods. In the first method, we will create a JSON file and in second method we will read the file and print in a text box.  If you like to know more about the basic entity of JSON you can check out Basic JSON entity here . What is JSON? JSON stands for J ava S cript O bject N otation JSON is a lightweight data-interchange format It is "self-describing" and easy to understand JSON is language independent and can we used in any language JSON Syntax Rules Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold