kotlin coroutine - 如何确保在协同程序内部调用时在UI主线程上运行某些命令?

问题描述 投票:0回答:1

我有一个非常简单的协程,只是做了一些延迟,然后我想要它做的是将命令发布到UI消息队列。所以在UI线程上运行最后两行。这是协程:

async{
    delay(5000)
    doSomething()
    doAnotherThing()
}

我想最后两个方法doSomething()和doAnotherThing()在UI线程上运行?如何才能做到这一点 ?从我所看到的延迟(5000)将自动异步运行但如何在UI线程上运行其余的?要非常清楚,我是从主线程启动的对象中执行此操作的。

kotlinx.coroutines
1个回答
2
投票

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()
    }
}

如果asyncDispatchers.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

© www.soinside.com 2019 - 2024. All rights reserved.