Dick Lucas
Dick Lucas

Reputation: 12639

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!

Upvotes: 4

Views: 2141

Answers (1)

Pavlo Ostasha
Pavlo Ostasha

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

Related Questions