首页 > 解决方案 > 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

标签: androidkotlinandroid-livedataandroid-jetpack

解决方案


您应该使用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 对象,否则不会计算转换。因为转换是延迟计算的,所以与生命周期相关的行为会被隐式传递,而不需要额外的显式调用或依赖项。


推荐阅读