Lifecycle Aware Data and Configuration change handling with LiveData

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
        if(clickMeViewModel.getClickCount()!=null){
            clickMe=clickMeViewModel.getClickCount();
        }
      //  else initialize with initial setup
        else{
            clickMe=0;
        }
        txtClickMe.setText("You Have Clicked " + clickMe + " Times");
        btnClickMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               clickMe++;
               txtClickMe.setText("You Have Clicked " + clickMe + " Times");
               //set the Click Count to ViewModel
               clickMeViewModel.setClickCount(clickMe);
            }
        });

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.

CounterViewModel.java
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;

    //Constructor
    public CounterViewModel(){
        Timer timer=new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                counter.postValue(InitCount++);
            }
        },ONE_SECOND,ONE_SECOND);
    }
    public MutableLiveData<Integer> getCounter() {
        return counter;
    }
}

Our main activity will look like as given below.

MainActivity.java
package com.nplix.livedataexample;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    CounterViewModel counterViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView counterTextView=findViewById(R.id.txtCounter);
        //Declare the Counter Data Model
        counterViewModel=
                ViewModelProviders.of(this).get(CounterViewModel.class);
        //Create the Observer for for Model
        Observer<Integer> dataObserver=new Observer<Integer>() {
            @Override
            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
        counterViewModel.getCounter().observe(this,dataObserver);

    }
}

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.

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

This Post Has 3 Comments

Leave a Reply

Close Menu