I am making an android application with Android Studio in Java. My goal is to be able to constantly check if a condition is true, for example if a variable is true it must take certain action. How can I always check this variable and not just once when starting the program?
CodePudding user response:
you can use code snippets like give below and put them into a thread which always run parallel to your main code
while(true)
{
if(_val) //_val is your boolean variable
{
// your logic
}
Thread.sleep(100);
}
Or an event can be raised on the click of that particular control which checks value of _val
and performs actions
Method 2: Use observable pattern: You can wrap a boolean in a class which you can listen for changes on.
class ObservableBoolean {
// "CopyOnWrite" to avoid concurrent modification exceptions in loop below.
private final List<ChangeListener> listeners =
new CopyOnWriteArrayList<ChangeListener>();
private boolean value;
public boolean getValue() {
return value;
}
public synchronized void setValue(boolean b) {
value = b;
for (ChangeListener cl : listeners)
cl.stateChanged(new ChangeEvent(this));
}
public synchronized void addChangeListener(ChangeListener cl) {
listeners.add(cl);
}
public synchronized void removeChangeListener(ChangeListener cl) {
listeners.remove(cl);
}
}
Then simply do:
ObservableBoolean b = new ObservableBoolean();
//...
// Start the "period of time":
b.addChangeListener(iWantToBeNotifiedOfChanges);
// ...
// End the "period of time":
b.removeChangeListener(iWantToBeNotifiedOfChanges);
This is actually a simple case of the MVC pattern (and the observer pattern). The model in this case is the ObservableBoolean and the view would be the "view" that wants to be notified of the changes.
You could also write your own ChangeListener
interface.
CodePudding user response:
You may use the LiveData for this purpose. Below is the sample usage of how you can do it.
MutableLiveData<boolean> boolToObserve = new MutableLiveData<boolean>();
// onCreate of Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
booltoObserve.observe(this, new Observer<boolean>() {
@Override
public void onChanged(@Nullable final boolean newValue) {
MyActivity.this.valueChanged(newValue);
}
}
}
This way, you do not need to take care of checking the value again and again. As soon as this value is changed from anywhere, your method will be called. Hope this helps.