简体   繁体   English

Transformations.map LiveData

[英]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 .) (此代码示例假定thisLifecyleOwner ,例如AppCompatActivity 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ViewModel,LiveData和Transformations.map - ViewModel, LiveData and Transformations.map 具有多个参数的 LiveData Transformations.map() - LiveData Transformations.map() with multiple arguments 可以在ViewModel内部由Transformations.map()返回的Livedata上调用observeForever()吗? - It is ok to call observeForever() on Livedata returned by Transformations.map() inside ViewModel? 使用 Transformations.map 在 ViewModel 中处理 Room 数据库中的 LiveData - Processing LiveData from Room database in ViewModel with Transformations.map LiveData 的 Transformations.map 未在单元测试中触发,并且仅在单元测试中触发 - LiveData's Transformations.map not being triggered in, and only in, Unit Tests LiveData,Transformations.map()-用户更改过滤顺序时如何强制刷新? - LiveData, Transformations.map() - How to force to refresh when the user changes filtering order? 使用 Transformations.map 替代 observeForever - Alternative for observeForever using Transformations.map Transformations.map() 返回 null 值 - Transformations.map() returns null values 我可以在 Kotlin 中用 Transformations.map 替换 _task.map 吗? - Can I replace _task.map with Transformations.map in Kotlin? 我对 Transformations.map 的绑定似乎不起作用 - My binding to a Transformations.map doesn't seem to be working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM