Transformations.map LiveData

Ali

New Member
#1
I have following code:
Mã:
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?
 

Admin

Administrator
Thành viên BQT
#2
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:
Mã:
res.observe(this, Observer { name ->
     textview.text = name
})
(This code sample assumes that this is a LifecyleOwner, such as an AppCompatActivity.)
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top