Viewmodel observing LiveData - how? Viewmodel observing LiveData - how? android android

Viewmodel observing LiveData - how?


I fixed this issue using MediatorLiveData. You can follow the steps below.

  1. Create a variable (ex. result).

    private final MediatorLiveData<Resource<RequestType>> result = new MediatorLiveData<>();
  2. Call addSource method where the first argument is LiveData 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));