Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback from viewmodel to ui without data

How can I have my viewmodel call a function in my activity or fragment without using a callback and where no data is actually sent. LiveData is used to send data from the viewmodel to the view but I have no data. I just want to notify the ui about something. Should this be done using RxJava or is that overkill?

like image 556
Johann Avatar asked Nov 07 '22 17:11

Johann


1 Answers

LiveData is just fine, here is what I did recently (derived from https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150)

first create a class

public class OneTimeEvent {

private Boolean received;

    public OneTimeEvent() {
        received = false;
    }

    public Boolean receive () {
        if (!received) {
            received = true;
            return true;
        }
        return false;
    }
}

then in your ViewModel expose your event

 private MediatorLiveData<OneTimeEvent> eventListener = new MediatorLiveData<>();

public LiveData<OneTimeEvent> onEvent() {
    return eventListener;
}

now you have to trigger the event somewhere in your ViewModel (like something else is finished)

eventListener.setValue(new OneTimeEvent()); //if its a background thread or callback use postValue!

that's it, now you can observe onEvent() in any activity or fragment you like

ViewModel.onEvent().observe(this,  new Observer<OneTimeEvent>() {
        @Override
        public void onChanged(OneTimeEvent oneTimeEvent) {
            if (oneTimeEvent.receive()){
                // do something on event
            }
        }
    });

Hope this helps, it acts just like an EventListener, only that you can Listen from Multiple Locations simultaneously, and each event will only be fired once, eg if the observer is reattached somewhere else.

like image 183
ueen Avatar answered Nov 12 '22 23:11

ueen