有没有办法知道你的协同程序是否已经从挂起函数中取消了



我使用的是CoroutineWorker,但我所有的业务逻辑都是一个单独的类,我开始使用suspend函数。我更愿意把所有的逻辑都保留在这个类中,但我需要知道工作请求是否已经取消。在suspend函数中,有没有什么方法可以知道它是否被取消了?

要确定当前Jobsuspend函数中是否仍处于活动状态(尚未完成且尚未取消(,可以使用isActive属性。示例:

suspend fun callApi() = withContext(Dispatchers.IO) {
//...
if (!isActive) {
// coroutine is not active
}
}

检查取消的另一种常见方法是调用ensureActive(),这是可用于JobCoroutineScopeCoroutineContext的扩展函数。示例:

suspend fun callApi() = withContext(Dispatchers.IO) {
//...
ensureActive() // it throws a CancellationException and will stop the execution
}

重复gmk57的答案:

"普通的suspend函数(没有withContext(不提供isActive标志,但您可以使用coroutineContext.isActive">

使用挂起功能,您确实可以访问corountineContext。访问它将使您可以直接在上下文中访问所有相同的属性。

您可以使用任一

coroutineScope { ensureActive() }
yield() // If this CPU heavy computation job.

最新更新