是否可以在观察者内部有一个协程来更新 UI?
例如:
Viewmodel.data.observer(this, Observer{ coroutinescope })
最佳答案
您可以从Observer
回调中运行您想要的任何代码。但是启动稍后更新 UI 的协程并不是一个好主意,因为当协程完成时,UI 可能会被破坏,这可能会导致抛出异常并使您的应用程序崩溃。
只需直接从 Observer
回调运行 UI 更新代码。
viewModel.data.observe(this, Observer {
// Update the UI here directly
})
这样一来,当您更新 UI 时,您就知道它是 Activity 的,因为 LiveData
考虑了 this
的生命周期。
如果您想在回调的同时启动一些协程,最好在您的 viewModel
中使用 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
}
请注意,您必须向 build.gradle
添加依赖才能使用 viewModelScope
:
dependencies {
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0'
}
关于Android Livedata Observer 协程 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326362/