简体   繁体   English

Kotlin协程异步延迟

[英]Kotlin coroutine async with delay

I'm wrapping my head around the coroutine concept in Kotlin/Android. 我把头放在Kotlin / Android中的协程概念上。 So, as I do not want to use Timertask, Handler with a post delayed I want to use coroutines to execute an async coroutine after a certain delay. 因此,由于我不想使用Timertask,所以处理程序延迟发布,我想使用协程在一定延迟后执行异步协程。 I have the following semi-code: 我有以下半代码:

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

    result.await()
 }

The problem with this is that actually in the async is both method's (delay and executeMethodAfterDelay) are executed at the same time. 问题是实际上在异步中,两个方法(delay和executeMethodAfterDelay)是同时执行的。 While I was expecting that first 30 seconds of delay would be introduced before executeMethodAfterDelay() would be fired. 当我期望在执行executeMethodAfterDelay()之前引入前30秒的延迟。 So my question is, how can I achieve this? 所以我的问题是,我怎样才能做到这一点?

Your code is too convoluted. 您的代码太复杂了。 You need just this: 您只需要这样:

launch(UI) {
    delay(30000)
    executeMethodAfterDelay()
}

If you specifically want your method to run outside the GUI thread, then write 如果您特别希望您的方法在GUI线程外运行,请编写

launch(CommonPool) {
    delay(30000)
    executeMethodAfterDelay()
}

More typically you'll want to execute a long-running method off the GUI thread and then apply its result to the GUI. 更典型地,您将需要在GUI线程上执行长时间运行的方法,然后将其结果应用于GUI。 This is how it's done: 这是这样做的:

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

Note you don't need async-await in any scenario. 注意,在任何情况下都不需要async-await


As for your specific report about delay running concurrently with executeMethodAfterDelay , this is not actually happening. 至于有关与executeMethodAfterDelay并发运行的delay的特定报告,这实际上并没有发生。 Here's some self-contained code you can try out: 您可以尝试以下一些自包含的代码:

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"

This will be the program's behavior: 这将是程序的行为:

Start the delay

... three seconds pass ... ...三秒钟过去了...

Execute the method
Method's result: method complete

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM