![](/img/trans.png)
[英]Best way to call suspend coroutine from Executor(ThreadPoolExecutor)
[英]Is there a way to know if your coroutine has been canceled from within a suspend function
我正在使用 CoroutineWorker,但我所有的业务逻辑都是一个单独的 class,我开始使用暂停 function。 我宁愿保留此 class 中的所有逻辑,但我需要知道工作请求是否已被取消。 如果它被取消,是否有某种方式知道暂停 function?
要确定当前Job
在suspend
function 中是否仍处于活动状态(尚未完成且尚未取消),您可以使用isActive
属性。 例子:
suspend fun callApi() = withContext(Dispatchers.IO) {
//...
if (!isActive) {
// coroutine is not active
}
}
检查取消的另一种常见方法是调用ensureActive()
,它是可用于Job
、 CoroutineScope
和CoroutineContext
。 例子:
suspend fun callApi() = withContext(Dispatchers.IO) {
//...
ensureActive() // it throws a CancellationException and will stop the execution
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.