gpt4 book ai didi

android - 等待 Kotlin 协程在 onCreateView() 中完成

转载 作者:行者123 更新时间:2023-12-02 02:23:11 25 4
gpt4 key购买 nike

我在 onCreateView 中有一个初始化 block ,其中一些变量是从 SharedPreferences、DB 或 Network(当前从 SharedPreferences)分配的。

我想用 onViewCreated 中的这些值更新 View 。但在 onCreateView 中的协程完成之前,它们会使用空值进行更新。如何在主线程中等待协程完成?

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
...
GlobalScope.launch(Dispatchers.Main) {
val job = GlobalScope.launch(Dispatchers.IO) {
val task = async(Dispatchers.IO) {
settingsInteractor.getStationSearchCountry().let {
countryName = it.name
}
settingsInteractor.getStationSearchRegion().let {
regionName = it.name
}
}
task.await()
}
job.join()
}
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

country.updateCaption(countryName)
region.updateCaption(regionName)
}

更新(2019年5月20日)

目前我不使用onViewCreated。我在 onCreateonCreateView 中编写代码。在 onCreateView 中,我通过以下方式访问 View :view.country.text = "abc" 等等。

最佳答案

最好使用async而不是launch https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html

创建lateinit val dataLoad: Deferred<Pair<String, String> 。将其初始化为 dataLoad = GlobalScope.async(Dispatchers.Defailt) {}onCreateView或更早。 launch UI 范围内的新协程 onViewCreated 。等待该协程的结果 val data = dataLoad.await()然后将数据应用到ui

关于android - 等待 Kotlin 协程在 onCreateView() 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53665470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com