Reputation: 12639
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!
Upvotes: 4
Views: 2141
Reputation: 16699
Something like
fun loadUser() {
user.value = User()
}
Listen to it via
myViewModel.getUser().observe(this, EventObserver { user ->
// do something with user
})
Hope it helps
Upvotes: 2