Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get notified of variable change using PropertyChangeSupport(e.g. observable, delegate)

I have this kind of issue I would like to listen to variable change. Lets take I have var foo:Int = 10 initialized and in the code somewhere it changes its value to something else lets take foo = 99 here is my code snippet in kotlin.

var foo:Int=10

private val changeSupport: PropertyChangeSupport? = PropertyChangeSupport(foo)

val observer = {
                    property: KProperty<*>,
                    oldValue: Int?,
                    newValue: Int? -> changeSupport!!.firePropertyChange(property.name, oldValue, newValue)
                }

 var oof: Int? by Delegates.observable(foo, observer)
 changeSupport!!.addPropertyChangeListener { event ->
                    Log.d("loggg","Property [${event.propertyName}] changed " + "from [${event.oldValue}] to [${event.newValue}]")
                }

So while somewhere in the code I write foo = 99 I have to receive the Log. I tried a lot of stuff I followed this articles but no success. Am I missing something?

How to create change listener for variable?

http://kotlination.com/kotlin/kotlin-observable-property-delegated-property https://www.javalobby.org/java/forums/t19476.html

like image 260
Armen Hovhannisian Avatar asked Dec 22 '25 09:12

Armen Hovhannisian


1 Answers

So the solution was simpler as I might think. I have to initially assign the variable with delegate and observable like this.

 var foo:Int? by Delegates.observable(10) { property, oldValue, newValue ->

            Log.d("loggg","gggol")

        }

and every time I call foo=something it logs the following output. Thanks.)

like image 131
Armen Hovhannisian Avatar answered Dec 23 '25 22:12

Armen Hovhannisian