簡體   English   中英

Kotlin協程異步延遲

[英]Kotlin coroutine async with delay

我把頭放在Kotlin / Android中的協程概念上。 因此,由於我不想使用Timertask,所以處理程序延遲發布,我想使用協程在一定延遲后執行異步協程。 我有以下半代碼:

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

    result.await()
 }

問題是實際上在異步中,兩個方法(delay和executeMethodAfterDelay)是同時執行的。 當我期望在執行executeMethodAfterDelay()之前引入前30秒的延遲。 所以我的問題是,我怎樣才能做到這一點?

您的代碼太復雜了。 您只需要這樣:

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

如果您特別希望您的方法在GUI線程外運行,請編寫

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

更典型地,您將需要在GUI線程上執行長時間運行的方法,然后將其結果應用於GUI。 這是這樣做的:

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

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


至於有關與executeMethodAfterDelay並發運行的delay的特定報告,這實際上並沒有發生。 您可以嘗試以下一些自包含的代碼:

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"

這將是程序的行為:

Start the delay

...三秒鍾過去了...

Execute the method
Method's result: method complete

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM