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
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.

Comments

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

    ReplyDelete
  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 […]

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

    ReplyDelete

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

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Scan and List All Available WiFi Network In Android

In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. You May Like Below Topic: How to Read and Write JSON data using GSON WP Android App using REST and volley WP Android App using REST and volley part2 Implementation of SwipeRefreshLayout in RecyclerView Create Amazing Bottom Navigation Bar Without Any External Library Introduction In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. We will add this functionality to our existing Demo app " Video Gallery ". If you would like to check out t