Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Livedata Observer Coroutine Kotlin

Is it possible to have a co-routine inside an observer to update the UI?

For Example:

Viewmodel.data.observer(this, Observer{ coroutinescope })
like image 867
Hoang Trung Nguyen Avatar asked Mar 19 '26 07:03

Hoang Trung Nguyen


1 Answers

You can run any code you want from the Observer callback. But it would not be a good idea to launch a coroutine that updates the UI later, because when the coroutine is complete, the UI might be destroyed, which can cause exceptions to be thrown and crash your app.

Just run the UI update code directly from the Observercallback.

viewModel.data.observe(this, Observer {
    // Update the UI here directly
})

That way you know that UI is alive when you update it, since LiveData takes the lifecycle of this into account.

If you want to launch some coroutine at the same time as the callback, it would be better to do it within your viewModel using viewModelScope.

// This triggers the above code
data.value = "foo"

// Now also launch a network request with a coroutine
viewModelScope.launch { 
    val moreData = api.doNetworkRequest()
    // Set the result in another LiveData
    otherLiveData.value = moreData
}

Note that you must add a dependency to build.gradle in order to use viewModelScope:

dependencies {
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0'
}
like image 152
Enselic Avatar answered Mar 21 '26 20:03

Enselic