首页 > 解决方案 > 如何从 MutableLiveData 发出不同的值?

问题描述

我观察到即使向其方法提供了相同的对象实例,也会MutableLiveData触发观察者。onChangedsetValue

//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)
        }
    }
}

标签: androidandroid-livedatamutablelivedata

解决方案


API中已经有:Transformations.distinctUntilChanged()

distinctUntilChanged

public static LiveData<X> distinctUntilChanged (LiveData<X> source)

创建一个新LiveData对象,在源 LiveData 值更改之前不会发出值。equals()如果yield ,则认为该值已更改 false

<<剪断余数>>


推荐阅读