Kotlin协程异步延迟

K R*_*eck 2 android coroutine kotlin kotlin-coroutines

我把头放在Kotlin / Android中的协程概念上。因此,由于我不想使用Timertask,所以处理程序延迟发布,我想使用协程在一定延迟后执行异步协程。我有以下半代码:

 launch(UI) {
    val result = async(CommonPool) { 
        delay(30000)
        executeMethodAfterDelay() 
    }

    result.await()
 }
Run Code Online (Sandbox Code Playgroud)

问题是实际上在异步中,两个方法(delay和executeMethodAfterDelay)是同时执行的。当我期望在执行executeMethodAfterDelay()之前引入前30秒的延迟。所以我的问题是,我怎样才能做到这一点?

Mar*_*nik 6

您的代码太复杂了。您只需要这样:

launch(UI) {
    delay(30000)
    executeMethodAfterDelay()
}
Run Code Online (Sandbox Code Playgroud)

如果您特别希望您的方法在GUI线程外运行,请编写

launch(CommonPool) {
    delay(30000)
    executeMethodAfterDelay()
}
Run Code Online (Sandbox Code Playgroud)

更典型地,您将需要在GUI线程上执行长时间运行的方法,然后将其结果应用于GUI。这是这样做的:

launch(UI) {
    delay(30000)
    val result = withContext(CommonPool) {
        executeMethodAfterDelay()
    }
    updateGuiWith(result)
}
Run Code Online (Sandbox Code Playgroud)

请注意,async-await在任何情况下都不需要。


至于您有关delay与并发运行的特定报告executeMethodAfterDelay,实际上并没有发生。您可以尝试以下一些自包含的代码:

import kotlinx.coroutines.experimental.*

fun main(args: Array<String>) {
    runBlocking {
        val deferred = async(CommonPool) {
            println("Start the delay")
            delay(3000)
            println("Execute the method")
            executeMethodAfterDelay()
        }
        val result = deferred.await()
        println("Method's result: $result")
    }
}

fun executeMethodAfterDelay() = "method complete"
Run Code Online (Sandbox Code Playgroud)

这将是程序的行为:

Start the delay
Run Code Online (Sandbox Code Playgroud)

...三秒钟过去了...

Execute the method
Method's result: method complete
Run Code Online (Sandbox Code Playgroud)