有没有可能在观察者内部有一个协同例程来更新UI?
例如:
Viewmodel.data.observer(this, Observer{ coroutinescope })发布于 2019-10-10 23:41:24
您可以从Observer回调中运行所需的任何代码。但稍后启动更新UI的协程并不是一个好主意,因为当协程完成时,UI可能会被销毁,这可能会导致抛出异常并使您的应用程序崩溃。
只需直接从Observer回调运行UI更新代码即可。
viewModel.data.observe(this, Observer {
// Update the UI here directly
})这样,当您更新UI时,您就知道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
}请注意,要使用viewModelScope,必须将依赖项添加到build.gradle
dependencies {
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0'
}发布于 2019-10-11 00:23:01
是的,这是可能的。您可以启动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)
}
}
})https://stackoverflow.com/questions/58326362
复制相似问题