首页 > 解决方案 > 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"

}

kotlin协程超过一定时间怎么取消?

标签: androidkotlin

解决方案


为此内置了暂停功能:withTimeoutwithTimeoutOrNull.

只需使用指定的超时调用它:

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

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

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


推荐阅读