What if you want to know when a delegated property has changed? For example, say that you want to react to the change and invoke some dependent code. This kind of listening behavior is often referred to as observing, and the Delegates object comes with the following appropriately named function to achieve exactly that:
fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit): ReadWriteProperty<Any?, T>
We can see this at work in the following simple example:
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
With the...