gpt4 book ai didi

android - 如何从 MutableLiveData 发出不同的值?

转载 作者:太空狗 更新时间:2023-10-29 15:58:05 28 4
gpt4 key购买 nike

我观察到 MutableLiveData 会触发观察者的 onChanged,即使向其 setValue 方法提供相同的对象实例也是如此。

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

最佳答案

API 中已有:Transformations.distinctUntilChanged()

distinctUntilChanged

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

Creates a new LiveData object does not emit a value until the source LiveData value has been changed. The value is considered changed if equals() yields false.

<<snip remainder>>

关于android - 如何从 MutableLiveData 发出不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54639282/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com