Skip to content Skip to sidebar Skip to footer

Android: Listening For Variable Changes

I've been searching for a KISS example of how to do this, and while they all seem (and I've gone through them ALL!) simple enough, I still cannot get my head around the concept. I

Solution 1:

You wrap the variable up inside a custom class such that the only access functions also trip the listener. So that the only way to flip the switch is via the functions which toggles and calls the listener.

publicclassBooVariable {
    privateboolean boo = false;
    privateChangeListener listener;

    publicbooleanisBoo() {
        return boo;
    }

    publicvoidsetBoo(boolean boo) {
        this.boo = boo;
        if (listener != null) listener.onChange();
    }

    publicChangeListenergetListener() {
        return listener;
    }

    publicvoidsetListener(ChangeListener listener) {
        this.listener = listener;
    }

    publicinterfaceChangeListener {
        voidonChange();
    }
}

To monitor the change you need to implement BooVariable.ChangeListener and then pass the BooVariable class a copy of "this" then, when you change the variable it calls onChange.

Also, keeping in mind you can just inline the code rather than extend directly:

BooVariablebv=newBooVariable();
bv.setListener(newBooVariable.ChangeListener() {
    @OverridepublicvoidonChange() {
        Toast.makeText(MainActivity.this,"blah", Toast.LENGTH_LONG).show();
     }
});

PS. The toast must be called from the UI thread, so you need to switch the Looper if you're going to change the variable in a different thread. This likely won't come up though.

Solution 2:

There is a much easier solution now. Just wrap your variable in a LiveData Specifically MutableLiveData.

Java Version

MutableLiveData<String> listen = newMutableLiveData<>();

listen.setValue("Changed value"); //Initilize with a value

listen.observe(context,newObserver<String>() {
    @OverridepublicvoidonChanged(String changedValue) {
        //Do something with the changed value
    }
});

Kotlin Version

val listen : MutableLiveData<String> =MutableLiveData<>()

listen.setValue("Changed value") //Initilize with a value

listen.observe(context, Observer {

    //Do something with the changed value -> it

})

Post a Comment for "Android: Listening For Variable Changes"