问题描述
我是Kotlin和协程的新手.但是我想用它来初始化Android ThreeTen backport库,这是一个长期运行的任务.我正在使用Metalab Async/Await库( co.metalab.asyncawait:asyncawait:1.0.0 ).
I'm new to Kotlin and the coroutines. However I want to use it to initialize the Android ThreeTen backport library which is a long running task. I'm using the Metalab Async/Await Library (co.metalab.asyncawait:asyncawait:1.0.0).
这是我的代码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val application = this
async {
//non-blocking initialize ThreeTen
await { AndroidThreeTen.init(application) }
//initialize UI on UI thread which uses the ThreeTen library
initUI()
}
}
现在我有一个问题,初始化UI时库没有初始化.据我了解,在调用AndroidThreeTen.init
之前不应该先调用initUI
.
Now I have the problem that the library is not initialized when initializing the UI. From my understanding initUI
shouldn't be called before AndroidThreeTen.init
is called.
推荐答案
简短的答案是,您不应为此使用Kotlin协程.
The short answer is that you should not use Kotlin coroutines for that.
长答案是,在初始化UI之前,您的代码需要在 之前初始化AndroidThreeTen,因此在尝试调用AndroidThreeTen.init
之前,必须先等待 完成还是initUI
.由于需要等待,因此没有理由使代码过于复杂.协程不是魔术.他们不会等待花费很多时间的事情,而以某种方式更快. AndroidThreeTen.init
使用协程或不使用协程将花费相同的时间.
The long answer is that your code needs AndroidThreeTen to be initialised before you initialise your UI, so you have to wait for AndroidThreeTen.init
to finish before trying to invoke initUI
anyway. Because of that inherent need to wait, there is little reason to overcomplicate your code. Coroutines are not magic. They will not make waiting for something that takes a lot of time somehow faster. AndroidThreeTen.init
will take the same amount of time with coroutines or without them.
您应该像这样编写代码:
You should just write your code like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val application = this
AndroidThreeTen.init(application)
initUI()
}
这篇关于异步不等待等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!