gpt4 book ai didi

android - MutableLiveData 到 MutableLiveData

转载 作者:搜寻专家 更新时间:2023-11-01 08:17:52 27 4
gpt4 key购买 nike

我如何转换 MutableLiveData< String>MutableLiveData< Int> .

 val text = NonNullMutableLiveData<String>("")

我的类 NonNullMutableLiveData:

 class NonNullMutableLiveData<T>(private val defaultValue: T) :
MutableLiveData<T>() {
override fun getValue(): T {
return super.getValue() ?: defaultValue
}
}

我想再添加一个MutableLiveData<Int>我在其中转换了 MutableLiveData<String> 的值

谢谢

最佳答案

您应该使用 Transformations.map 来获取 intLiveData。

val intLiveData = Transformations.map(textLiveData) {
try {
it.toInt()
} catch (e: NumberFormatException) {
0
}
}

然后 intLiveData.value 可能仍然为 null,即使 textLivaData.value 已经是“2”。因为 intLiveDataintLiveData 被观察和激活之前不会改变。

这意味着你应该设置一个观察者到intLiveData,并等待观察者开始。

intLiveData.observe(lifecycleOwner,  Observer{ intValue ->
// get the int value.
})

作为google说,

You can use transformation methods to carry information across the observer's lifecycle. The transformations aren't calculated unless an observer is watching the returned LiveData object. Because the transformations are calculated lazily, lifecycle-related behavior is implicitly passed down without requiring additional explicit calls or dependencies.

关于android - MutableLiveData<String> 到 MutableLiveData<Int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969834/

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