我有一个初始化块onCreateView
,其中一些变量是从 SharedPreferences、DB 或 Network(当前从 SharedPreferences)分配的。
我想用这些值更新视图onViewCreated
。但它们在协程之前更新为空值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)
}
更新(20-05-2019)
目前我不使用onViewCreated
。我在中编写代码onCreate
and onCreateView
. In onCreateView
我这样访问视图:view.country.text = "abc"
等等。
最好用async
代替launch
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html.
Create lateinit val dataLoad: Deferred<Pair<String, String>
。将其初始化为dataLoad = GlobalScope.async(Dispatchers.Defailt) {}
in onCreateView
或更早。launch
UI 范围内的新协程onViewCreated
。等待该协程的结果val data = dataLoad.await()
然后将数据应用到ui
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)