I am now using the recent Android Architecture Components and in particular the ViewModel and LiveData.
I am in a case where the SingleLiveEvent suggested here is relevant, i.e. I am returning an error and I want to display an alert only once. Before emitting a value to the Activity, I need to map my error to a more appropriate object for the view. I am using a Transformation for this.
So in the end, I have a ViewModel that looks like:
public LiveData<ViewState> getStateForView() {
final LiveData<NetworkState> liveState = myRepository.getState();
return Transformations.map(liveState, myMapper::map);
}
Where in my repository I am using a SingleLiveEvent:
public LiveData<NetworkState> getState() {
myNetworkState = new SingleLiveEvent<>();
return myNetworkState;
}
This works fairly well but I notice that my event is not propagated all the time when orientation changes multiple times. When debugging, I have noticed that there is no symmetry between the observer registration and removal:
- at registration time the observer of my SingleLiveEvent is the anonymous Observer class in my SingleLiveEvent
- at removal time the observer to be removed from my SingleLiveEvent is a MediatorLiveData (which is actually observing the earlier anonymous class in my SingleLiveEvent)
What happens is that my initial observer is never removed from the observers of the SingleLiveEvent (so if orientation changes multiple times my SingleLiveEvent has multiple observers).
I cannot figure out why this is not the same observer at removal time. When reproducing it without a Transformation step, there is no such issue.
Does anyone have a hint about this behaviour? Are SingleLiveEvent (not part of the framework) and Transformations not supposed to work together?