我有一个非常简单的协程,只是做了一些延迟,然后我想要它做的是将命令发布到UI消息队列。所以在UI线程上运行最后两行。这是协程:
async{
delay(5000)
doSomething()
doAnotherThing()
}
我想最后两个方法doSomething()和doAnotherThing()在UI线程上运行?如何才能做到这一点 ?从我所看到的延迟(5000)将自动异步运行但如何在UI线程上运行其余的?要非常清楚,我是从主线程启动的对象中执行此操作的。
async
创建一个协程并在Coroutine上下文中运行,继承自CoroutineScope
,可以使用context参数指定其他上下文元素。如果上下文没有任何调度程序或任何其他ContinuationInterceptor
,则使用Dispatchers.Default
。
如果使用Dispatchers.Default
,那么无论你在async
构建器中调用什么函数,它都将异步运行。要切换上下文,可以使用withContext
函数:
async {
delay(5000)
withContext(Dispatchers.Main) {
// if we use `Dispatchers.Main` as a coroutine context next two lines will be executed on UI thread.
doSomething()
doAnotherThing()
}
}
如果async
在Dispatchers.Main
上下文中运行,则不需要切换上下文:
var job: Job = Job()
var scope = CoroutineScope(Dispatchers.Main + job)
scope.async {
delay(5000) // suspends the coroutine without blocking UI thread
// runs on UI thread
doSomething()
doAnotherThing()
}
注意:async
主要用于并行执行。开始使用简单的协程launch
构建器。因此,您可以在async
函数中替换这些示例中的所有launch
函数。另外要使用async
构建器运行协同程序,您需要在await()
函数上调用Deferred
函数调用async
函数。 Here is some additional info。