Zoom Webinar: Learn and enhance your TypeScript skills | 28th March 2023 | 10 AM PST [10:30 PM IST] Register here
Functionalities

LiveData: An Android Architecture Development Component

logo

DhiWise

July 12, 2021
image
Author
logo

DhiWise

{
July 12, 2021
}

LiveData is the android architecture component that simplifies reactive programming for responsive UI development. In this article, you will learn about LiveData, its importance in android development, and how to work with it in Kotlin.

In Android development, Live Data is one of the core Android architecture components essential for reactive programming. It is a simple yet powerful component that changes your UI based on some data.

For Example, if you want to show the number of followers for the user profile in your social media application, with the dynamic values that change when someone follows or unfollows your account. These changes can be carried out with the help of the ViewModel.

Google has introduced the concept of LiveData to ease the working of ViewModel. Let us know more about it.

Kotlin Live Data

What is Live Data?

LiveData is a Library in Lifecycle 2.0, which is now a part of Android Jetpack (A set of components, tools, and guidance designed to accelerate app development). LiveData is an observable data holder class, which means it is aware of the lifecycle of other application components such as, activities, fragments, and services.

UI observes the LiveData objects to show the data on the screen. Therefore, when the LiveData changes, UI gets notified, and then UI updates itself with the LiveData changes. In a nutshell, LiveData synchronizes the UI with the updated data.

Importance of Live Data

If the lifecycle status is STARTED or RESUMED, LiveData considers an observer to be in an active state. Only active observers are notified of lifecycle updates by LiveData. Inactive observers who have registered to watch the LiveData objects, on the other hand, are not notified of status updates.

LiveData is an important android architectural component because,

  1. It eliminates memory leaks caused by the multiple callbacks that send results to the UI thread, ensuring that the UI is always up to date.
  2. It de-couples tight integration between data, mediator, and the UI to avoid crashed activities.
  3. UI components continuously monitor relevant data, and LiveData manages all of these tasks automatically as the relevant lifecycle status changes.
  4. If the activity or fragment is recreated due to configuration changes such as device rotation(Portrait, Landscape), it immediately receives the latest information from LiveData.
  5. Extended Live Data wraps system services so that they can be shared within the app. The live data object connects to the system service only once, and then any observer that needs the resource can watch LiveData and get it updated. After which any observer who requires the resource can watch LiveData get updated.

Therefore it plays an important role in the MVVM architectural pattern.

Live Data 2

Working with LiveData in Kotlin

Here are the fundamental steps for getting started with LiveData Objects in Kotlin.

  1. First, you need to create an instance of a LiveData inside the ViewModel class to hold data.
  2. Then, in the UI controller, create an Observer object that defines the method onChange (). It is in charge of controlling data changes in the LiveData object.
  3. Finally, using the observe() method, connect the Observer object to the LiveData object. In observation, you need to define all the changes in the UI that you want to perform on data changes.

When the value stored in the LiveData object changes, the change is notified to all observers associated with the LiveData once they enter the resume state.

Let’s see how we can code for the above steps.

1. Creating an Instance of a LiveData

LiveData is a wrapper that can be used with any data, including the objects which can be observed from the UI components i.e. ViewModel via getter method as demonstrated in the example below.

class NameViewModel : ViewModel() {
// Create a LiveData with a String
val currentName: MutableLiveData< String > by lazy {
MutableLiveData()
}
// Rest of the ViewModel…
}

In the above code, LiveData declared as val can be changed, but you can update the value of LiveData because it is MutableLiveData. Any changes in its value will notify all of its active observers.

2. Creating an Observer Object

To begin observing LiveData objects, go to the method onCreate(). This is because it ensures that the system doesn’t make redundant calls from an activity or fragment onResume method() and the activity and fragment must have data that it can display once it is active.

In general, LiveData notifies changes to the active Observers only when they receive updates on the data. However, there is one exception; observers receive updates as they transition from inactive to active status.

Further, if the observer changes inactive to active state a second time, in such a case it will be notified only if the value has changed since the last time it became active.

Here is a code sample that illustrates how to start observing LiveData objects.

class NameActivity : AppCompatActivity() {
// Use the ‘by viewModels()’ Kotlin property delegate
// from the activity-ktx artifact
private val model: NameViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Other code to set up the activity…
// Create the observer which updates the UI.
val nameObserver = Observer< String> { newName ->
// Update the UI, in this case, a TextView.
nameTextView.text = newName
}
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
model.currentName.observe(this, nameObserver)
}
}

3. Updating LiveData Object

LiveData lacks public methods for updating its stored values. As a result, you can use MutableLiveData to publicly update the value inside LiveData using the setValue() and postValue() methods.

  • setValue sets the value instantly. The main thread calls setValue to perform this synchronous update.
  • postValue: It doesn’t guarantee instant updates to the observer. When the observer doesn’t receive instant updates, then it is called asynchronous updating. When calling the Observer more than once from the background thread, the observer only dispatches the latest value to the downstream.

You can update the value of the LiveData object as shown in the code sample below.

button.setOnClickListener {
val anotherName = “John Doe”
model.currentName.setValue(anotherName)
}

This is how you can use LiveData in reactive programming.

App users expect responsive UI components that immediately respond to the changes in related data for interactive user experience. LiveData library enables developers to make such changes to the UI to improve user satisfaction and brand experience.

Finding ways to simplify your Android development? Try DhiWise Kotlin Builder!!

DhiWise is a 100% developer-centric platform that supports Android architecture development components(MVVM). As a result, you will be able to build your app more quickly. Start using the DhiWise Kotlin builder and generate your code automatically.