[将MediatorLiveData的值设置为对添加到ViewModel的构造函数中的源或ViewModel的活动onCreate观察器中的源做出反应时,例如这样:
showingMethodLiveData.addSource(stateChangeLiveData) {
when (it) {
ConfigurationState.CURRENT -> showingMethodLiveData.value = commMethod[it]
ConfigurationState.PENDING -> showingMethodLiveData.value = commMethod[it]
}
}
尽管已调用set方法,但未将值设置为观察视图。我可以通过以下方法解决此问题:在onStart中添加源(这会导致多次注册观察者的其他问题),或者使用postValue而不是setValue。
setValue方法的调试使我进入以下代码,其中有一个有趣的注释可以讲述故事,该方法返回时未将值设置为绑定视图。
在androidx.databinding生命周期依赖包中:类ViewDataBinding:
private void handleFieldChange(int mLocalFieldId, Object object, int fieldId) {
if (mInLiveDataRegisterObserver) {
// We're in LiveData registration, which always results in a field change
// that we can ignore. The value will be read immediately after anyway, so
// there is no need to be dirty.
return;
}
boolean result = onFieldChange(mLocalFieldId, object, fieldId);
if (result) {
requestRebind();
}
}
此后也不会设置该值,仅在通过更改其源再次调用mediatorlivedata时才设置。为什么会出现这种情况?谢谢你的帮助
Mediatorlivedata的用途是比较两个值,然后提供结果。如果要更改变量的值,只需使用MutableLiveData并分配一个新值,请输入variableName.value = newValue
这样应该更容易实现:
val showingMethodLiveData = Transformations.map(stateChangeLiveData) { commMethod[it] }