我注意到即使将相同的对象实例提供给其
setValue
方法,MutableLiveData
仍会触发观察者的onChanged
方法。//Fragment#onCreateView - scenario1
val newValue = "newValue"
mutableLiveData.setValue(newValue) //triggers observer
mutableLiveData.setValue(newValue) //triggers observer
//Fragment#onCreateView - scenario2
val newValue = "newValue"
mutableLiveData.postValue(newValue) //triggers observer
mutableLiveData.postValue(newValue) //does not trigger observer
如果在setValue()
/postValue()
中提供相同或等效的实例,有没有办法避免观察者被通知两次?
我尝试扩展MutableLiveData
,但没有成功。可能我漏掉了什么。
class DistinctLiveData<T> : MutableLiveData<T>() {
private var cached: T? = null
@Synchronized override fun setValue(value: T) {
if(value != cached) {
cached = value
super.setValue(value)
}
}
@Synchronized override fun postValue(value: T) {
if(value != cached) {
cached = value
super.postValue(value)
}
}
}
Transformations.distingUntilChanged()
方法最早在 Ver 2.1.0 中可用,但该版本尚未稳定发布! https://developer.android.com/jetpack/androidx/releases/lifecycle#2.1.0-alpha01 - ASP