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...