January 2017
Intermediate to advanced
420 pages
9h 25m
English
What if you want to know when the delegated property is changed? You might need to react to the change and call some other code. The Delegates object comes with the following construct to allow you to achieve exactly that:
fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit): ReadWriteProperty<Any?, T>
We will see this at work with the following simple example. Every time the value property is changed, the onValueChanged() method is called and we print out the new value:
class WithObservableProp {
var value: Int by Delegates.observable(0) { p, oldNew, newVal -> onValueChanged()
}
private fun onValueChanged() {
println("value has changed:$value") } } val ...Read now
Unlock full access