Android Architecture Components: How to use LiveData with Data Binding

Databinding and livedata is the part of Android architecutre component.

Databinding is a library which is used to bind data in the layout. It also remove boilerplate code like findviewbyid() method.

Livedata is a lifecycle aware observable data holder which will provide always updated data to the UI.

Today we will see how data binding can observe livedata updates.

To use LiveData object with your databinding we must need to use lifecycle owner when observe livedata from data binding layout.

// include layout in fragment
dataBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_test,container,false)
dataBinding!!.lifecycleOwner = viewLifecycleOwner  // use this for activity
viewModel = ViewModelProvider(this).get(
dataBinding!!.viewModel = viewModel
return dataBinding!!.root

Then after you only need to observe livedata updates in layout

<TextView style="@style/TextStyleRegular"

and in TestViewModel you need to do

private val _strAlertMessage = MutableLiveData()
var strAlertMessage: LiveData = _strAlertMessage
fun showAlertMessage(alert: String) {
_strAlertMessage.value = alert

and call showAlertMessage() method in your fragment then see you binding layout will automatically observe alert message in textview. That’s all so simple.

Leave a Reply