Android Livedata Observer 协程 Kotlin
Android Livedata Observer Coroutine Kotlin
是否可以在观察者内部有一个协程来更新UI?
例如:
Viewmodel.data.observer(this, Observer{ coroutinescope })
您可以 运行 来自 Observer
回调的任何代码。但是稍后启动一个更新 UI 的协程并不是一个好主意,因为当协程完成时,UI 可能会被销毁,这可能会导致抛出异常并使您的应用程序崩溃.
只是 运行 UI 直接从 Observer
回调中更新代码。
viewModel.data.observe(this, Observer {
// Update the UI here directly
})
这样你就知道 UI 在你更新时还活着,因为 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'
}
是的,这是可能的。您可以启动一个 GlobalScope 协程,当您需要更新 UI 时,您应该在 activity!!.runOnUiThread
这里是示例。
viewModel.phoneNumber.observe(this, Observer { phoneNumber ->
GlobalScope.launch {
delay(1000L) //Wait a moment (1 Second)
activity!!.runOnUiThread {
binding.textviewPhoneLabel.edittextName.setText(phoneNumber)
}
}
})
是否可以在观察者内部有一个协程来更新UI?
例如:
Viewmodel.data.observer(this, Observer{ coroutinescope })
您可以 运行 来自 Observer
回调的任何代码。但是稍后启动一个更新 UI 的协程并不是一个好主意,因为当协程完成时,UI 可能会被销毁,这可能会导致抛出异常并使您的应用程序崩溃.
只是 运行 UI 直接从 Observer
回调中更新代码。
viewModel.data.observe(this, Observer {
// Update the UI here directly
})
这样你就知道 UI 在你更新时还活着,因为 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'
}
是的,这是可能的。您可以启动一个 GlobalScope 协程,当您需要更新 UI 时,您应该在 activity!!.runOnUiThread
这里是示例。
viewModel.phoneNumber.observe(this, Observer { phoneNumber ->
GlobalScope.launch {
delay(1000L) //Wait a moment (1 Second)
activity!!.runOnUiThread {
binding.textviewPhoneLabel.edittextName.setText(phoneNumber)
}
}
})