For the More Curious: LiveData and Data Binding

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 = sound
                notifyChange()
                title.postValue(sound?.name)
            }

        @get:Bindable
        val title: String?
            get() = sound?.name
    }

In this example, it is no longer necessary to subclass BaseObservable or provide ...

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.