Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emit() LiveData results to an existing LiveData object?

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!

like image 297
Dick Lucas Avatar asked Sep 18 '25 06:09

Dick Lucas


1 Answers

Something like

fun loadUser() {
     user.value = User()
}

Listen to it via

 myViewModel.getUser().observe(this, EventObserver { user ->
     // do something with user
 })

Hope it helps

like image 167
Pavlo Ostasha Avatar answered Sep 20 '25 20:09

Pavlo Ostasha