Kotlin Delegated Property – Observable Property

In this Kotlin tutorial, we’re gonna look at how to make an observable property by using Kotlin delegated property.

>>> Refer to: JavaSampleApproach.com

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Overview

We will create an example that can notify listener when a property of an object changes.

Java has a mechanism for this notification: PropertyChangeSupport class manages a list of listeners and dispatches PropertyChangeEvent events to them.

To use it, we will create a helper class that will store a PropertyChangeSupport instance and keep track of PropertyChangeListener.

Then the class that has property to be notified will extend this helper class:

name is read-only property
– everytime age or message is changed, class will notify its listeners via observer with PropertyChangeSupport.firePropertyChange() method:

property is represented as an object of type KProperty. We can access the name of the property as KProperty.name.

Add listener to Person object using PropertyChangeAware.addPropertyChangeListener() method or remove listener using PropertyChangeAware.removePropertyChangeListener() method:

Now, everytime we change value of the property, PropertyChangeEvent event will be dispatched to listener.

III. Practice

1. Helper Class

2. Class with delegated property

3. Run and check Result

Run the code below:

Check Result:

Add Comment