![](/img/trans.png)
[英]Implement Redux with Android Observer/Livedata/Coroutine/Kotlin
[英]Android Livedata Observer Coroutine Kotlin
是否可以在观察者内部有一个协程来更新 UI
例如:
Viewmodel.data.observer(this, Observer{ coroutinescope })
你可以从Observer
回调中运行任何你想要的代码。 但是稍后启动一个更新 UI 的协程并不是一个好主意,因为当协程完成时,UI 可能会被破坏,这可能会导致抛出异常并使您的应用程序崩溃。
只需直接从Observer
回调中运行 UI 更新代码。
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 时,您应该在活动中。!runOnUiThread
这里有一个样本。
viewModel.phoneNumber.observe(this, Observer { phoneNumber ->
GlobalScope.launch {
delay(1000L) //Wait a moment (1 Second)
activity!!.runOnUiThread {
binding.textviewPhoneLabel.edittextName.setText(phoneNumber)
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.