LiveData is an observable data class. It is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. It is in an active state if its lifecycle is in the started or resumed state. In a passive state, it holds data and is notified when it observes in an active state. This is especially useful for activities and fragments because they can safely observe it. During use of it not to worry about the memory leaks, because activities and fragments are instantly unsubscribed when their lifecycles are destroyed.
How To use With Mvvm?
As LiveData is a data holder class that is used to observe the changes of a ViewModel and update those changes. As it is lifecycle-aware, it means that whenever data is updated or changed, the changes are only applied to the specific app components that are in an active state. Contrarily, if the app components are inactive, the changes will not be applied.
Why do we need it?
It resolving mainly two issues: It removes the leaks caused by the interfaces/callbacks that send results to the UI thread. This is a core feature of an MVVM model where callbacks are sent from ViewModel to activity/fragment. It de-couples tight integration between data, mediator, and the UI layers.
Types in LiveData
There are subclasses in LiveData.
LiveData is immutable by default. By using LiveData we can only observe the data and cannot set the data.
MutableLiveData is mutable and is a subclass of LiveData. In MutableLiveData we can observe and set the values using postValue() and setValue() methods so that we can use post values to any live data variable.
MediatorLiveData can observe other LiveData objects such as sources and react to their onChange() events. It will give us control over when we want to perform an action in a particular event.
But in some scenarios, like when we need to perform UI updates by clicking on a particular View to perform validations or show a progress bar during server call, we go with SingleLiveEvent.
SingleLiveEvent is a subclass of MutableLiveData. It is aware of the View’s lifecycle and can observe the data with a single Observer.
Benefits of using LiveData
No more manual lifecycle handling
Always up to date data
No memory leaks
Ensures your UI matches data state
Increased stability of code
Decoupling issue removed between UI and data.
Basic steps to work with LiveData
Step 1: Create an instance of LiveData
val mDestinationForward = MutableLiveData<String>()
Step 2: Set the data in LiveData
We are using two methods for passing data to live data.
If we are working on the main thread we can use both methods. But, on a background thread, we can use only postValue to set data in LiveData.
LiveData reduces boilerplate code for UI updates in the application. The LiveData completely solves the major problems like orientation change issues, LiveData also ensures that the UI is always up to date even when the app’s configuration is changed.