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. 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.
null.toString()
which the result is the string "null"
And the other hand, when you use LiveData the right approach is to observe all changes like zsmb13 suggested.
res.observe(this, Observer { name -> textview.text = name })
LiveData
works asynchronously. The value you've set for it isn't immediately available in the transformed LiveData
. Instead of trying to read that value directly, you should observe
its changes, then you'll get the latest values:
res.observe(this, Observer { name ->
textview.text = name
})
(This code sample assumes that this
is a LifecyleOwner
, such as an AppCompatActivity
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.