Android LiveData - switchMap is not triggered on second update
I was trying to do something similar to you. I have a LiveData something
, and when that changes I want to query somethingElse
from the DB based on a property. Because the property can be null, if I query the DB with it, I'll get an exception. Therefore, if the property is null, I'm returning an empty MutableLiveData.
I have noticed, that when I returned this empty MutableLiveData, the observers that subscribed to somethingElse
were not getting any updates. I saw that on your answer you ended up using a MediatorLiveData. Then I steped through my code with the debugger and noticed that the switchMap also uses a MediatorLiveData.
After experimenting a bit, I realised that when creating the empty MutableLiveData, it's initial value is null and won't trigger any updates. If I explicitly set the value, then it will notify the observers.
somethingElse = Transformations.switchMap(something, somethingObject -> {
if (something.someProperty() != null) {
return repository.getSomethingElseByProperty(something.someProperty());
}else{
MutableLiveData<SomethingElse> empty = new MutableLiveData<>();
empty.setValue(null);//need to set a value, to force update of observers
return empty;
}
The code here has worked for me. In the question, you use an AbsentLiveData, which I don't know how it is implemented, so I'm not sure it would work exactly in that case.