Observables
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 onChange = WithObservableProp() onChange.value = 10 onChange.value = -20
There is another observable implementation offered out of...