I wish to call a function in Java when a value of particular variable is changed. I do not want to constantly check the value of the variable by setting a time interval, e.g. whenever the value of variable A becomes 1, just call function A. Is there any way to create a Listener for a value of variable?
Asked
Active
Viewed 267 times
-1
-
Execute the action from your setter? There is an Observable api? What do you mean when the variable is changed? – matt Sep 11 '20 at 10:56
-
when a value of variable is changed to some specific value , i wish to create a listener that would call a particular method – tomtom Sep 11 '20 at 10:58
-
1Actually don't use the [Observable](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Observable.html) api it is deprecated, they suggest the java.beans or some data structures in java.concurrent – matt Sep 11 '20 at 10:59
1 Answers
0
If you are using the JavaFX (OpenJFX) library, there is the Property class.
IntProperty a = new SimpleIntProperty();
a.addListener((observable, oldValue, newValue) ->
System.out.printf("%d -> %d%n", oldValue, newValue);
a.set(42);
A property wraps some object or type.
In general better use a reactive model like Flow.

Joop Eggen
- 107,315
- 7
- 83
- 138