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"
}
kotlin协程超过一定时间怎么取消?
解决方案
为此内置了暂停功能:withTimeout
和withTimeoutOrNull
.
只需使用指定的超时调用它:
GlobalScope.launch(Dispatchers.Main) {
val userOne = withContext(Dispatchers.IO) {
withTimeoutOrNull(5000) { Page_Load_Times() }
}
Log.d("Tag", "Long Running task: $userOne")
}
如果它超时,那么你userOne
就变成了。null
推荐阅读
- architecture - 我应该如何组织我的微服务以通过 CloudFormation 实现独立部署
- scala - scala - 如何根据另一列的值向 Dataframe 添加新列?
- bazel - bazel 中的大型/巨大测试目标和并行性
- ibm-midrange - 阻止对 AS400 文件的更新和删除操作
- javascript - 如何在可视化脚本的帮助下循环进入 blend4web?
- mips - 10*($a0+4) 与 MIPS 汇编指令
- firebase - 在 FireStore 中实施餐厅评级系统
- android - 由于 TransactionTooLargeException,ADB 内容查询 SMS 失败
- c++ - 我应该使用什么类型的?
- c# - 从 .Net 库调用的异步任务中潜在挂起的问题