LiveData in Android
Introduction -
LiveData is a part of Android Jetpack. LiveData is simply a data holder but it is observable. It observes if there is a change in data. LiveData is lifecycle-aware, if there is a change then LiveData will update the corresponding application components such as activities, fragments or services, which are active. If the application components are not active, then LiveData will send the updated data in future. So you don't have to worry about the lifecycle of the application components.
There are two types of LiveData
- Mutable LiveData (Object of MutableLiveData) - We can change the live data.
- Immutable LiveData (Object of LiveData) - We cannot change the live data.
Application -
- It can be used for Room Persistent Library, Coroutines etc.
- Once a data is changed, the corresponding application components will be notified automatically.
- If the corresponding application components is not active, then it will be notified in the future with the latest data. We don't have to worry about application crash due to inactive application components.
- You don't have to worry about screen rotation.
- You don't have to worry about unsubscribing any observers (application components).
Follow these steps for LiveData -
- Add the required dependencies in build.gradle (Module) file.
// ViewModel and LiveData
def lifecycle_version = "2.4.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
- Create an object of LiveData in your ViewModel.
class MainViewModel : ViewModel() {
private val factsLiveDataObject = MutableLiveData<String>("This is a fact")
val factsLiveData: LiveData<String>
get() = factsLiveDataObject
fun updateLiveData() {
factsLiveDataObject.value = "Another Data"
}
}
- In the above code, we have used the immutable live data (Object of LiveData) which is exposed to the user. The object of mutable live data is used in backend.
- Set the data in LiveData using setValue() and postValue() methods.
When we are working on main thread, the both setValue() and postValue() will work in the same manner. i.e. they will update the value and notify the application components.
When we are working on some background thread then we can't use setValue(), we have to use postValue() on some application components.
viewmodel.name.setValue(/*Updated data*/);
viewmodel.name.postValue(/*Updated data*/);
- Add the reference in MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainViewModel = ViewModelProvider(this)[MainViewModel::class.java]
mainViewModel.factsLiveData.observe(this, Observer {
tvUpdate.text = it
})
btnUpdate.setOnClickListener {
mainViewModel.updateLiveData()
}
}
}
Comments
Post a Comment