android - 如何从 MutableLiveData 发出不同的值?
问题描述
我观察到即使向其方法提供了相同的对象实例,也会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)
创建一个新
LiveData
对象,在源 LiveData 值更改之前不会发出值。equals()
如果yield ,则认为该值已更改false
。<<剪断余数>>
推荐阅读
- r - 使用 dplyr 在每个组中循环以创建逐步曲线
- php - 如何将 PHP 变量封装在字符串中?(在 POST 请求正文中)
- node.js - 间距大于0的Mapbox gl原生拼接图块
- c++ - 用正整数填充数组
- jsf - 如何使用 PrimeFaces Diagram 导出图像文件
- rest - 无法通过 JAVA REST API 连接到雪花
- c++ - C++:从文件中读取 xy 数据会创建无限循环?
- git - 如何构建符合 GDPR 的基于 git 的静态页面?
- c - typedef 的用途是什么,它的正确用途是什么?
- json - 将 JSON 转换为 CSV1,然后将输出与另一个 CSV2、vb.net 进行比较