Architecture Components: How to use LiveData with Data Binding?

Photo credits: flickr.com

Setup

buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0-alpha06'
}
}
kapt 'com.android.databinding:compiler:3.1.0-alpha06'

How to use it?

val kittyName = ObservableField<String>()
val kittyAge = ObservableInt()

init {
kittyRepository.receiveNewKitties {
kittyName.set(it.name)
kittyAge.set(it.age)
}
}
val kittyName = MutableLiveData<String>()
val kittyAge = MutableLiveData<Int>()

init {
kittyRepository.receiveNewKitties {
kittyName.postValue(it.name)
kittyAge.postValue(it.age)
}
}
val binding: ActivityMainBinding = ...
binding.setLifecycleOwner(this)

Ok, but what does it change?

init {
kittyRepository.receiveNewKitties {
Log
.d("MainViewModel", "Generating kitty name: " + it.name)
...
}
}
kittyNameText.addAfterTextChangedListener { Log.d("MainActivity",
"Showing kitty name: " + it) }
D/MainViewModel: Generating kitty name: TIGER
D/MainActivity: Showing kitty name: TIGER
D/MainViewModel: Generating kitty name: FLUFFY
D/MainActivity: Showing kitty name: FLUFFY
D/MainViewModel: Generating kitty name: PUMPKIN
D/MainViewModel: Generating kitty name: TIGER

Flutter GDE / Android & Flutter Developer / blogger / speaker / cat owner / travel enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store