Transformations.map 实时数据

Transformations.map LiveData

我有以下代码:

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"
}

我希望它打印 Ali Ali 但它打印了一个空值。我错过了什么?

LiveData 异步工作。您为其设置的值不会立即在转换后的 LiveData 中可用。不要试图直接读取该值,您应该 observe 它的更改,然后您将获得最新的值:

res.observe(this, Observer { name ->
     textview.text = name
})

(此代码示例假定 thisLifecyleOwner,例如 AppCompatActivity。)

您缺少空检查。

res.value.toString() 想象一下当 res.value 为 null 时您正在执行此操作的情况。

null.toString() 结果是字符串 "null"

另一方面,当您使用 LiveData 时,正确的方法是像 zsmb13 建议的那样观察所有变化。

res.observe(this, Observer { name -> textview.text = name })