LiveData-Android Architecture Components

  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) {


}
});


}
}
<?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>
LiveDataObject 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());
}
};
liveDataObject.getUserDetailsMutableLiveData().observe(this, userDetailsObserver);
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);
}
});

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suraj Vishwakarma

Suraj Vishwakarma

17 Followers

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