In an Android app (or Java more generally if it's no different), what is the best way of calling a method whenever a variable's value changes?
What you really want to do is set up event-driven model to trigger a listener when an event happen (in your case, say a variable value has changed). This is very common not only for Java, but for other programming languages as well especially in the context of UI programming (though it is not necessarily only for that)
Typically this is done by doing the following steps:
public interface VariableChangeListener { public void onVariableChanged(Object... variableThatHasChanged); }
You could put any argument that you think it is important for the listener to handle here. By abstracting into the interface, you have flexibility of implementing the necessary action in the case of variable has changed without tight coupling it with the class where the event is occurring.
// while I only provide an example with one listener in this method, in many cases // you could have a List of Listeners which get triggered in order as the event // occurres public void setVariableChangeListener(VariableChangeListener variableChangeListener) { this.variableChangeListener = variableChangeListener; }
By default there is no one listening to the event
if( variableValue != previousValue && this.variableChangeListener != null) { // call the listener here, note that we don't want to a strong coupling // between the listener and where the event is occurring. With this pattern // the code has the flexibility of assigning the listener this.variableChangeListener.onVariableChanged(variableValue); }
Again this is a very common practice in programming to basically reacts to an event or variable change. In Javascript you see this is as part of onclick(), in Android you could check the event driven model for various listener such as OnClickListener set on a Button onclick event. In your case you will just trigger the listener based on different event which is whenever the variable has changed
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