Trending Articles       10 Flutter Listview Examples       Flutter Custom Button Example       Flutter Audio Recording       Flutter 2.0 Autocomplete TextField       Current Location Google Maps

Android Jetpack Tutorials : LiveData

LiveData Overview
LiveData is an observable data packaging class. Unlike ordinary observers, LiveData has life cycle awareness, which means that it follows the life cycle of other application components (Activity, Fragment, Service, etc.). This ensures that LiveData is only updated. Observers of components that are active in the life cycle

LiveData will only update the observers in the active state, while the registered observers in the inactive state will not be updated.

We can register an observer in an object that implements the LifecycleOwner interface. This association allows the observer to be automatically removed when its related Lifecycle object is in the DESTROYED state, especially activities and fragments. They can safely observe LiveData without worrying about memory. Leakage-activities and fragments will immediately cancel the data observation subscription when the life cycle is destroyed

LiveData advantages
Ensure UI and data status are synchronized
LiveData follows the observer pattern. When the life cycle state changes, LiveData notifies the Observer object. You can merge code to update the UI in these Observer objects. Every time the application data changes, your observer can update the UI every time it changes, instead of updating the UI

No memory leak
Observers are bound to Lifecycle objects and clean up themselves after their associated lifecycle is destroyed

Won't crash because the activity stopped
If the observer's life cycle is inactive, such as in the case of activity in the backend stack, it will not receive any LiveData events

No longer need to manually handle life cycle
The UI component only observes related data, and does not stop or resume observation. LiveData automatically manages all of this because it is aware of related life cycle state changes when observing

Always keep data up to date
If the life cycle becomes inactive, it will receive the latest data when it becomes active again. For example, background activities receive the latest data immediately after returning to the foreground

Configuration change friendly
If an event or clip is recreated due to configuration changes (such as device rotation), the latest available data will be received immediately

Resource Sharing
You can use the singleton pattern to extend LiveData objects to wrap system services so that they can be shared among applications. The LiveData object is connected to the system service once, and then any observer who needs the resource can only watch the LiveData object

Use LiveData
The general steps for using LiveData are as follows, we follow these steps to write a simple example:

1. Create a LiveData instance of any type, this step is usually done in the ViewModel

2. Create an Observer objects and override its onChanged()method, which will be called back and returns the latest data when LiveData data changes, this step is usually done in the UI controller

3, using the observer()method associated Observer and LiveData, observer()method of holding LifecycleOwner objects, this subscription will LiveData notify Observer variation in the data, this step is usually done in the UI controller

Note: You can use the observeForever(Observer) method to register observers without associated LifecycleOwner objects. In this case, the observer is considered to be always active and therefore will always receive notification about the modification. You can delete the observer through the removeObserver(Observer) method


Example LiveData with ViewModel

Step 1: Create Android application

Step 2: Add Dependencies

def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"


Step 3: Create ViewModel Repository
package com.rrtutors.androidviewmodel.livedata;

import java.util.Random;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class LiveDataViewModel extends ViewModel {

    private MutableLiveData<String>mutableLiveData;

    public MutableLiveData<String>getData()
        if(mutableLiveData==null) {
            mutableLiveData = new MutableLiveData<>();
        return  mutableLiveData;

    public void createRandomNumber()
            mutableLiveData=new MutableLiveData<>();

        Random random=new Random();
        mutableLiveData.setValue("Number: "+(random.nextInt(10-1)+1));


Step 4: Create ViewModel instance and fetch data from ViewModel

Update activity class with below code

package com.rrtutors.androidviewmodel.livedata;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.rrtutors.androidviewmodel.R;

public class LiveDataActivity extends AppCompatActivity {

    TextView textview;
    Button button;
    LiveDataViewModel liveDataViewModel;
    protected void onCreate(Bundle savedInstanceState) {

         liveDataViewModel= new ViewModelProvider(this).get(LiveDataViewModel.class);

        final MutableLiveData<String>mutableLiveData=  liveDataViewModel.getData();
        mutableLiveData.observe(this, new Observer<String>() {
            public void onChanged(String s) {
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {



Check the Data on configura changes, example on rotation of the device the data fetch from ViewModle instance not create new instance of every rotation.

ViewModel instance will only destroy once the parent activity of viewmodel completly destroy.

LiveData with ViewModel


Author: RRTutors

Flutter Questions

Android Questions