LiveData in Android Architecture Components
Last Updated :
17 Mar, 2025
LiveData is one of the android architecture components. LiveData is an observable data holder class. What is the meaning of observable here the observable means live data can be observed by other components like activity and fragments (Ui Controller). The most important thing about LiveData is it has the knowledge about the Life cycle of its observers like activity or fragment. That means Live data only updates the app components like Activity or Fragments which are in active life cycle state. LiveData notifies the observer(Activity or Fragment) which are in Started or Resumed life cycle state. Inactive observers registered to watch LiveData objects aren’t notified about changes. Here inactive observers mean which are not in the state of Started or Resumed. One can register an observer paired with an object that implements the LifecycleOwner interface which we will see in our example. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to DESTROYED.
This component is an observable data holder class i.e, the contained value can be observed. LiveData is a lifecycle-aware component and thus it performs its functions according to the lifecycle state of other application components. Further, if the observer’s lifecycle state is active i.e., either STARTED or RESUMED, only then LiveData updates the app component. LiveData always checks the observer’s state before making any update to ensure that the observer must be active to receive it. If the observer’s lifecycle state is destroyed, LiveData is capable to remove it, and thus it avoids memory leaks. It makes the task of data synchronization easier.

It is necessary to implement onActive and onInactive methods by LiveData:
Kotlin
class LocationLiveData(context: Context): LiveData<Location>(), AnkoLogger, LocationListener {
private val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE)
as LocationManager
override fun onActive() {
info(“onActive”)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, this)
}
override fun onInactive() {
info(“onInactive”)
locationManager.removeUpdates(this)
}
}
In order to observe a LiveData Component observer(LifecycleOwner, Observer<T>) method is called:
Kotlin
fun observeLocation() {
val location = LocationLiveData(this)
location.observe(this,
Observer { location ->
info(“location: $location”)
})
}
}
Implementation in Android App
In this example we will just create a simple counter app, that just counts 5 seconds, you can do anything using LiveData but for now let’s build this small app.
Step 1: Add these dependencies in your build.gradle file
dependencies {
...
implementation ("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
implementation ("androidx.lifecycle:lifecycle-livedata-ktx:2.8.7")
implementation ("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
implementation ("androidx.core:core-ktx:1.15.0")
}
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
activity_main.xml:
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="48sp"
android:textColor="@color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Create a ViewModel class
Create a Kotlin class file MainViewModel.kt. Our MainActivity class file extends the ViewModel class.
MainViewModel.kt:
Kotlin
package org.geeksforgeeks.demo
import android.os.CountDownTimer
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MainViewModel:ViewModel() {
private val _seconds = MutableLiveData<Int>()
private val _finished = MutableLiveData<Boolean>()
// getter method for seconds var
fun seconds(): LiveData<Int> {
return _seconds
}
// getter method for finished var
fun finished():LiveData<Boolean>{
return _finished
}
// Counter method that uses CountDownTimer()
fun startCounter(){
// Can change the millisInFuture value
object : CountDownTimer(5000, 100) {
override fun onTick(millisUntilFinished: Long) {
val time = millisUntilFinished / 1000
// setting the count value
_seconds.value = time.toInt()
}
override fun onFinish() {
// if millisInFuture completed
// it set the value true
_finished.value = true
}
}.start()
}
}
Note: Here we are using MutableLiveData right. but the question is why? because there is already LiveData is available, MutableLiveData extends LiveData class and two functions setValue() and postValue() are publicly available for use.
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file.
MainActivity.kt:
Kotlin
package org.geeksforgeeks.demo
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// create instance of ViewModel class
val viewModel = ViewModelProvider(this)[MainViewModel::class.java]
// calling start counter methods which is in our viewmodel class
viewModel.startCounter()
val textView: TextView = findViewById(R.id.textView)
// observing the second value of our view model class
viewModel.seconds().observe(this) {
textView.text = "$it"
}
viewModel.finished().observe(this) {
if (it) {
// if count time finished it set the value
textView.text = "Finished"
}
}
}
}
Note: Here inside Observe() “this” is the Life cycle owner as we discussed above to observe the value, we should pass the Lifecycle Owner. Here this means MainActivity which is the observer here.
Output:
Advantages of Using LiveData
- No need to update UI every time: LiveData follows the observer pattern. LiveData notifies Observer objects when there is any change occurs.
- No memory leaks: Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.
- No more manual lifecycle handling: UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.
- Proper configuration changes: If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.
Similar Reads
Jetpack Architecture Components in Android
Android Jetpack is a set of software components, libraries, tools, and guidance to help in developing robust Android applications. Launched by Google in 2018, Jetpack comprises existing android support libraries, android architecture components with an addition of the Android KTX library as a single
10 min read
Lifecycle in Android Architecture Components
Lifecycle is one of the Android Architecture Components which was released by Google to make it easier for all the Android developers. The Lifecycle is a class/interface which holds the information about the state of an activity/fragment and also it allows other objects to observe this state by keep
4 min read
ViewModel in Android Architecture Components
ViewModel is part of the android architecture component. Android architecture components are the components that are used to build robust, clean, and scalable apps. Android architecture components hold some classes to manage UI components and Data persistence. The ViewModel class is designed to stor
5 min read
Overview of Room in Android Architecture Components
Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-lev
5 min read
Overview of Paging in Android Architecture Components
The Paging library allows you to load and show pages of data from a bigger dataset that is stored locally or over the network. This method helps your program to make better use of both network bandwidth and system resources. The Paging library's components are built to fit into the suggested Android
3 min read
What is Clean Architecture in Android?
With the growing period of technology, it is critical to get the architecture right if you want to build a fantastic software program, which is why itâs so essential. If youâre interested in creating android apps with the help of clean architecture, then you have arrived at the right place. Here, we
5 min read
Overview of WorkManager in Android Architecture Components
Android WorkManager could be thought of as a backgrounding library that is employed to execute background tasks that should run in a guaranteed way but not necessarily immediately. With WorkManager we'll enqueue our backgrounding even when the app isn't running and even when the device is rebooted f
4 min read
Overview of Navigation in Android Architecture Components
Navigation basically in mobile development refers to the interaction between different screens or pieces of contents within the application. Android Jetpack's architecture Component the Navigation is so powerful, providing a consistent and predictable user experience. The navigation component helps
5 min read
Overview of Data Binding in Android Architecture Components
This article describes the concept behind the Data Binding and MVVM Design Pattern and its components. To try it, open or find a project with messy and unmanageable code, then attempt to use the MVVM components introduced in this article. In many ways, we haven't seen much changes in the software de
4 min read
Android Architecture Patterns
Modern mobile applications are dynamic, evolving over time to meet user needs. As these apps gets complex day by day, it becomes essential to separate core logic from UI components (such as activities and fragments). To structure the project's code and to give it a modular design(separated code part
5 min read