The coroutine LiveData example in the official Android developer docs gives the following example using emit():
val user: LiveData<User> = liveData {
val data = database.loadUser() // loadUser is a suspend function.
emit(data)
}
Every example of emit() I have seen including this ProAndroidDev tutorial creates a new LiveData object when using emit(). How can I get a LiveDataScope from a LiveData object that has already been created and emit() values to it? E.g.
class MyViewModel : ViewModel() {
private val user: MutableLiveData<User> = MutableLiveData()
fun getUser(): LiveData<User> {
return user
}
fun loadUser() {
// Code to emit() values to existing user LiveData object.
}
Thanks so much and all help is greatly appreciated!
Something like
fun loadUser() {
user.value = User()
}
Listen to it via
myViewModel.getUser().observe(this, EventObserver { user ->
// do something with user
})
Hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With