Observing property value change with Delegates.Observable

Delegates are not only for initializing properties lately/lazily. As we learned, delegation enables the forwarding of getter and setter calls of a property to the delegate. This enables delegates to offer more cool features than just lately/lazily initialization.

One such cool feature comes with Delegates.observable. Think of a situation where you need to look out for the value change of a property, and perform some action as soon as this occurs. The immediate solution that comes to our mind is to override the setter, but this would look nasty and make codes complex, whereas delegates are there to save our life.

Have a look at the following example:

var myStr:String by Delegates.observable("<Initial Value>") { 
    property, oldValue, newValue -> 
    println("Property `${property.name}` changed value from "$oldValue" to "$newValue"") 
} 
 
fun main(args: Array<String>) { 
    myStr = "Change Value" 
    myStr = "Change Value again" 
} 

It's a simple example, we declared a String property—myStr, with the help of Delegates.observable (we will describe that initialization soon after having a look at the output), then, inside the main function, we changed the value of myStr twice.

Have a look at the following output:

In the output, we can see, that for both times we changed the value, a log got printed with the old and new value of the property. The Delegates.observable block in this program is responsible for that log in the output. So now, let's have a close look at the Delegates.observable block and understand how it works:

var myStr:String by Delegates.observable("<Initial Value>") { 
    property, oldValue, newValue -> 
    println("Property `${property.name}` changed value from "$oldValue" to "$newValue"") 
} 

The Delegates.observable function takes two parameters to create the delegate. The first argument is the initial value of the property, and the second argument is the lambda that should be executed whenever the value change is noticed.

The lambda for Delegates.observable expects three parameters:

  • The first one is an instance of KProperty<out R>
KProperty is an interface in the Kotlin stdlib, kotlin.reflect package, it is a property; such as a named val or var declaration. Instances of this class are obtainable by the :: operator. For more information, visit: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-property/.
  • The second parameter contains the old value of the property (the last value just before the assignment)
  • The third parameter is the newest value assigned to the property (the new value used in the assignment)

So, as we've got the concept of Delegates.observable, let's move ahead with a new delegate, Delegates.vetoable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.7.240