What are the use cases for Delegates.observable
when we can just use property setters?
var foo by Delegates.observable("hell0") { prop, old, new -> // react to changes in foo } var bar = "hello" set(value) { field = value // react to changes in bar // we can also do validation, set something like `value*2` to field, etc. }
The observable delegate allows for a lambda to be triggered any time the value of the property changes, for example allowing for change notifications or updating of other related properties: class ObservedProperty { var name: String by Delegates .observable ( "<not set>") { prop, old, new -> println ( "Old value: $old, New value: $new" ) } }
A property can delegate its getter and setter to another property. Such delegation is available for both top-level and class properties (member and extension). The delegate property can be: To delegate a property to another property, use the :: qualifier in the delegate name, for example, this::delegate or MyClass::delegate.
Delegated properties are used by declaring the property and the delegate that it uses. The by keyword indicates that the property is controlled by the provided delegate instead of its own field. This uses the fact that a MutableMap is itself a delegate, allowing you to treat its keys as properties. 3. Standard Delegated Properties
The expression after by is a delegate, because the get () (and set ()) that correspond to the property will be delegated to its getValue () and setValue () methods. Property delegates don’t have to implement an interface, but they have to provide a getValue () function (and setValue () for var s).
Property setters require much more code duplication if you want multiple properties to react to modification in the same way:
var foo: Foo = Foo() set(value) { println("foo = $value") field = value } var bar: Bar = Bar() set(value) { println("bar = $value") field = value }
Delegates, in turn, are aimed to allow for reuse of the property accessors logic, like this:
fun <T> printDelegate(init: T) = Delegates.observable(init) { prop, _, new -> println("${prop.name} = $new") } val foo: Foo by printDelegate(Foo()) val bar: Bar by printDelegate(Bar())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With