关于android:Kotlin coroutine async with delay

Kotlin coroutine async with delay

我正在围绕Kotlin / Android中的协程概念。 所以,因为我不想使用Timertask,Handler延迟了一个帖子,我想在一定的延迟后使用协同程序来执行异步协程。 我有以下半代码:

1
2
3
4
5
6
7
8
 launch(UI) {
    val result = async(CommonPool) {
        delay(30000)
        executeMethodAfterDelay()
    }

    result.await()
 }

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


你的代码太复杂了。 你需要这个:

1
2
3
4
launch(UI) {
    delay(30000)
    executeMethodAfterDelay()
}

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

1
2
3
4
launch(CommonPool) {
    delay(30000)
    executeMethodAfterDelay()
}

更典型的是,您需要从GUI线程执行长时间运行的方法,然后将其结果应用于GUI。 这就是它的完成方式:

1
2
3
4
5
6
7
launch(UI) {
    delay(30000)
    val result = withContext(CommonPool) {
        executeMethodAfterDelay()
    }
    updateGuiWith(result)
}

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

至于与executeMethodAfterDelay同时运行的delay的具体报告,实际上并没有发生这种情况。 以下是您可以尝试的一些自包含代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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"

这将是该计划的行为:

1
Start the delay

......三秒钟过...

1
2
Execute the method
Method's result: method complete