【问题标题】:Is there a way to know if your coroutine has been canceled from within a suspend function有没有办法知道您的协程是否已从挂起函数中取消
【发布时间】:2023-02-10 07:31:23
【问题描述】:

我使用的是 CoroutineWorker,但我所有的业务逻辑都是一个单独的类,我开始使用一个挂起函数。我更愿意将所有逻辑保留在此类中,但我需要知道工作请求是否已被取消。如果它已被取消,是否有某种方式可以在挂起功能中知道?

【问题讨论】:

  • 请提供足够的代码,以便其他人可以更好地理解或重现问题。
  • 如果您的暂停功能是异步的,它将立即被取消

标签: android kotlin kotlin-coroutines coroutine android-workmanager


【解决方案1】:

要确定suspend 函数中当前的Job 是否仍然处于活动状态(尚未完成且尚未取消),您可以使用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
}

【讨论】:

  • 普通suspend函数(没有withContext)不提供isActive标志,但您可以使用coroutineContext.isActive
【解决方案2】:

重复 gmk57 的回答:

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

通过暂停功能,您可以访问您的corountineContext。访问它将使您能够访问所有可以直接从上下文中访问的相同属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-17
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2019-04-05
    • 2015-02-13
    相关资源
    最近更新 更多