kotlin协程耗时超过一定时间如何取消?

Rif*_*fat 3 android kotlin

如果 kotlin 协程花费的时间超过一定时间,我想取消它。

这就是我正在做的:

    GlobalScope.launch(Dispatchers.Main) {
        val userOne = async(Dispatchers.IO) { Page_Load_Times() }.await()

        Log.d("Tag", "Long Running task: $userOne")
    }


suspend fun Page_Load_Times(): String? {
    val startTime: Long = 0
    var endTime: Long = 0

    delay(5000) // if it is greater a certain time, eg 1000, I want to cancel the thread and return 

    return "Hey there"

}
Run Code Online (Sandbox Code Playgroud)

kotlin协程耗时超过一定时间如何取消?

Paw*_*wel 5

有内置的暂停函数:withTimeoutwithTimeoutOrNull

只需在指定的超时时间内调用它即可:

GlobalScope.launch(Dispatchers.Main) {
    val userOne = withContext(Dispatchers.IO) {
        withTimeoutOrNull(5000) { Page_Load_Times() }
    }

    Log.d("Tag", "Long Running task: $userOne")
}
Run Code Online (Sandbox Code Playgroud)

如果超时,那么你的userOne就变成了。null