LiveData and data binding are similar in that they both provide a way to observe data and react when that data changes. In fact, it is possible to work with both LiveData and data binding together, in tandem. The example below shows the changes that you would make to SoundViewModel to bind the title property as LiveData instead of an Observable property.
class SoundViewModel: BaseObservable(){ val title: MutableLiveData<String?> = MutableLiveData() var sound: Sound? = null set(sound) { field = soundnotifyChange()title.postValue(sound?.name) }@get:Bindableval title: String?get() = sound?.name}
In this example, it is no longer necessary to subclass BaseObservable or provide @Bindable
annotations, because LiveData has its own mechanisms for notifying observers.
However, as you learned in Chapter 11, LiveData does require a LifecycleOwner.
To tell the data binding framework which lifecycle owner to use when observing the title property, you would update SoundAdapter, setting the lifecycleOwner property after creating the binding:
private inner class SoundAdapter(private val sounds: List<Sound>) :
RecyclerView.Adapter<SoundHolder>() {
...
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
SoundHolder {
val binding = DataBindingUtil.inflate<ListItemSoundBinding>(
layoutInflater,
R.layout.list_item_sound,
parent,
false
)
binding.lifecycleOwner = this@MainActivity
return SoundHolder(binding)
}
}
This would set MainActivity as the lifecycle owner. No changes to the view would be required as long as the property name, title, remained the same.