Viewmodel observing LiveData - how?
I fixed this issue using MediatorLiveData
. You can follow the steps below.
Create a variable (ex. result).
private final MediatorLiveData<Resource<RequestType>> result = new MediatorLiveData<>();
Call
addSource
method where the first argument isLiveData
and the second is an observer.LiveData<Resource<EmptyResponse>> observable = service.createItems();result.addSource(observable, response -> { //Write code here }
Also see this SO answer. The basic requirement is almost the same.
You can use Transformations to invoke actions if one of your LiveData Objects changes.
E.g. the user selects a person in a Spinner
and you want to load the according person object.
MutableLiveData<Integer> personId = new MutableLiveData<>();LiveData<Person> person = Transformations.switchMap(personId, id -> getPerson(id));