![](/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.