Search code examples
androidandroid-architecture-componentsandroid-livedataandroid-architecture-lifecycle

Android LiveData - switchMap is not triggered on second update


I have a LiveData object that depends on another LiveData. As I understand, Transformations.switchMap should allow to chain them. But switchMap handler is triggered only once and it doesn't react on further updates. If instead I use observe on the first object and, when it's ready, retrieve the second, it works fine but in this case I have to do it in Activity rather than ViewModel. Is it possible to chain LiveData objects, like Transformations.switchMap, but receive all updates, not only the first one?

Here is an attempt to use switchMap:

LiveData<Resource<User>> userLiveData = usersRepository.get();
return Transformations.switchMap(userLiveData, resource -> {
    if (resource.status == Status.SUCCESS && resource.data != null) {
        return apiService.cartItems("Bearer " + resource.data.token);
    } else {
        return AbsentLiveData.create();
    }
});

Here is an approach with observe in activity (works but requires to keep logic in activity):

viewModel.user().observe(this, x -> {
    if (x != null && x.data != null) {
        viewModel.items(x.data.token).observe(this, result -> {
            // use result
        });
    }
});

Solution

  • As a workaround, I used MediatorLiveData. I add the result of the first call as a source and, when it's ready, replace it with a final call:

    MediatorLiveData<MyResponse> result = new MediatorLiveData<>();
    LiveData<Resource<User>> source = this.get();
    result.addSource(source, resource -> {
        if (resource.status == Status.SUCCESS && resource.data != null) {
            result.removeSource(source);
            result.addSource(apiService.cartItems("Bearer " + resource.data.token), result::postValue);
        }
    });
    return result;