android - MutableLiveData to MutableLiveData
问题描述
How could I convert MutableLiveData< String>
to MutableLiveData< Int>
.
val text = NonNullMutableLiveData<String>("")
My class NonNullMutableLiveData:
class NonNullMutableLiveData<T>(private val defaultValue: T) :
MutableLiveData<T>() {
override fun getValue(): T {
return super.getValue() ?: defaultValue
}
}
I would like to add another MutableLiveData<Int>
in which I have transformed value of MutableLiveData<String>
Thanks
解决方案
您应该使用Transformations.map
来获取 intLiveData。
val intLiveData = Transformations.map(textLiveData) {
try {
it.toInt()
} catch (e: NumberFormatException) {
0
}
}
然后intLiveData.value
可能仍然为空,即使textLivaData.value
已经是“2”。因为在被观察和激活intLiveData
之前不会改变。intLiveData
这意味着您应该将观察者设置为intLiveData
,并等待观察者启动。
intLiveData.observe(lifecycleOwner, Observer{ intValue ->
// get the int value.
})
正如谷歌所说,
您可以使用转换方法在观察者的生命周期中传递信息。除非观察者正在观看返回的 LiveData 对象,否则不会计算转换。因为转换是延迟计算的,所以与生命周期相关的行为会被隐式传递,而不需要额外的显式调用或依赖项。
推荐阅读
- postgresql - 致命:找不到所需的检查点记录
- c# - IP 日志记录为 2FA?'void' 到 'string' 和 'Form1.getMyIPAddress()' 的问题
- c++ - 输出没有临时的返回对
- android - React Native 运行没有错误不会在设备上启动?
- javascript - 在没有 Jquery 的情况下对 mouseEnter 和 mouseLeave 做出反应停止/开始淡出
- linux - 从 Linux 服务器向 Google Cloud Platform 进行身份验证
- mysql - 如何在 mySQL 中查找最常见的字符串
- javascript - 为什么我的 div 没有更新它们的背景颜色?
- node.js - 在 lambdas/箭头函数中抛出没有大括号的错误
- python - 熊猫查询没有返回正确的DataFrame Python