[英]Transformations.map LiveData
I have following code : 我有以下代码:
val liveData = MutableLiveData<String>()
liveData.value = "Ali"
val res = map(liveData) { post(it) }
textview.text = res.value.toString()
fun post(name: String): String {
return "$name $name"
}
I expect it to print Ali Ali
but it prints a null value. 我希望它可以打印Ali Ali
但它会打印一个空值。 What am I missing? 我想念什么?
You are missing a null check. 您缺少空检查。
res.value.toString()
Imagine the case when res.value is null you are doing this. res.value.toString()
想象一下,当res.value为null时,您正在这样做。
null.toString()
which the result is the string "null" null.toString()
,其结果是字符串“ null”
And the other hand, when you use LiveData the right approach is to observe all changes like zsmb13 suggested. 另一方面,使用LiveData时,正确的方法是观察所有建议的zsmb13更改。
res.observe(this, Observer { name -> textview.text = name })
LiveData
works asynchronously. LiveData
异步工作。 The value you've set for it isn't immediately available in the transformed LiveData
. 您为它设置的值在转换后的LiveData
不会立即可用。 Instead of trying to read that value directly, you should observe
its changes, then you'll get the latest values: 您应该observe
它的变化,而不是尝试直接读取该值,然后您将获得最新的值:
res.observe(this, Observer { name ->
textview.text = name
})
(This code sample assumes that this
is a LifecyleOwner
, such as an AppCompatActivity
.) (此代码示例假定this
是LifecyleOwner
,例如AppCompatActivity
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.