LiveData-Android Architecture Components

Suraj Vishwakarma
3 min readOct 19, 2019

--

This section will help you to understand the concept of LiveData in Android Architecture Components. We will be covering what is live data, Advantages of live data, Basic implementation of live data like creating the object, Observing object, Updating UI.

Github Link :https://github.com/surajvish/livedata.git

  1. Introduction
  2. Advantages
  3. Implementation

Introduction

Live Data is an Observable class that is the same as other observable. Live Data is a lifecycle aware class which means it method declare in Activity, Fragment and Services follows the rule of the lifecycle

Advantages

  1. Data state
  2. No memory leaks
  3. Handle configuration changes

Data state

When we update the value in data. LiveData updated the same in UI as well from which we can say that Live Data follow the rule of Observer Pattern which notifies the Observer when there is a change in object.

No Memory Leaks

From the introduction we come to know that Live data is an observable holder class and lifecycle aware component so it will get destroy when lifecycle get destoryed

Handle configuration changes

If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.

Implementation

Let us create a sample example to understand Live Data in android.

Step-1

Let us add the supporting lib in build.gradle file as shown below

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'android.arch.lifecycle:extensions:1.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

Step -2

Let us create a POJO class which we will use in MutableLiveData. I have created UserDetails class as shown below

public class UserDetails {
private String name;
private int age;

public UserDetails(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}
}

Step -3

Let us create a LiveData wrapper class. Which can be done by extending the class using ViewModel because LiveData is stored in ViewModel

public class LiveDataObject extends ViewModel {
private MutableLiveData<UserDetails> userDetailsMutableLiveData;

public MutableLiveData<UserDetails> getUserDetailsMutableLiveData() {
if (userDetailsMutableLiveData == null) {

userDetailsMutableLiveData = new MutableLiveData<UserDetails>();
}
return userDetailsMutableLiveData;
}

}

Step -4

Let us create an Activity which will have two text view, two Edittext and a button which will update the value in textview

public class MainActivity extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final EditText edtName = findViewById(R.id.edt_username);
final EditText edtAge = findViewById(R.id.edt_age);

final TextView txtUserName = findViewById(R.id.username);
final TextView txtAge = findViewById(R.id.age);

findViewById(R.id.clickMe).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {


}
});


}
}

Below is the xml file of the activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>

<EditText
android:id="@+id/edt_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Enter Username"
android:padding="10dp"
/>

<EditText
android:id="@+id/edt_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Enter Age"
android:padding="10dp"
/>
</LinearLayout>


<Button
android:id="@+id/clickMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
></Button>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>

<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Hello World!"
/>

<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Hello World!"
/>
</LinearLayout>

</LinearLayout>

Let us create an LiveDataObject object. Which can be done as show below

LiveDataObject liveDataObject = ViewModelProviders.of(this).get(LiveDataObject.class);

Now let use create an Observer which will notify whenever value gets the update in LiveData and the same we are updating in TextView as shown below.

final Observer<UserDetails> userDetailsObserver = new Observer<UserDetails>() {

@Override
public void onChanged(UserDetails userDetails) {
txtUserName.setText(userDetails.getName());
txtAge.setText("" + userDetails.getAge());
}
};

Now we have reach to last step. We will create and observe for LiveData as show below.

liveDataObject.getUserDetailsMutableLiveData().observe(this, userDetailsObserver);

Complete code

public class MainActivity extends AppCompatActivity {

LiveDataObject liveDataObject;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final EditText edtName = findViewById(R.id.edt_username);
final EditText edtAge = findViewById(R.id.edt_age);

final TextView txtUserName = findViewById(R.id.username);
final TextView txtAge = findViewById(R.id.age);


liveDataObject = ViewModelProviders.of(this).get(LiveDataObject.class);
final Observer<UserDetails> userDetailsObserver = new Observer<UserDetails>() {

@Override
public void onChanged(UserDetails userDetails) {
txtUserName.setText(userDetails.getName());
txtAge.setText("" + userDetails.getAge());
}
};

findViewById(R.id.clickMe).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {


}
});

liveDataObject.getUserDetailsMutableLiveData().observe(this, userDetailsObserver);
}
}

Step-5

Let us add the action on which we will be updating the value in Livedata object. And the same will get notify the observer from which we will update the value in textview.

findViewById(R.id.clickMe).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

UserDetails userDetails = new UserDetails(edtName.getText().toString(), Integer.parseInt(edtAge.getText().toString()));
liveDataObject.getUserDetailsMutableLiveData().setValue(userDetails);
}
});

Github Link : https://github.com/surajvish/livedata.git

--

--

Suraj Vishwakarma

Mobile Application Developer | Flutter Developer | Project Manager | Team Leader | Scrum Certified | PMI APC Appeard | Writing (starting soon)