当onStopped是最终版本时,如何在CoroutineWorker中执行清除代码?

时间:2019-07-12 17:14:46

标签: android-workmanager

我已升级到WorkManager 2.1.0,并尝试使用包括CoroutineWorker在内的某些Kotlin扩展。我的工作人员先前在扩展androidx.work.Worker,并且正在通过覆盖onStopped执行清除代码。为什么onStoppedCoroutineWorker中是最后的? CoroutineWorker停止后,我还有其他方法可以执行清除代码吗?

根据this blog post,这应该是一项功能吗?

2 个答案:

答案 0 :(得分:2)

您始终可以使用job.invokeOnCompletetion,而不必依赖onStopped的{​​{1}}回调。例如。

CoroutineWorker

答案 1 :(得分:1)

来自 Kotlin 文档:

<块引用>

可取消的挂起函数会在取消时抛出 CancellationException 异常,这可以用通常的方式处理。例如, try {...} finally {...} 表达式和 Kotlin use 函数在协程被取消时正常执行它们的终结操作。 Coroutines documentation

这意味着您可以使用通常的 Java/Kotlin 方式使用 try 和 finally 清理协程代码:

    override suspend fun doWork(): Result {
        return try {
            work()
            Result.success()
        } catch (e: Exception) {
            Result.failure()
        } finally {
            cleanup()
        }
    }

请注意,您不能在 catch 和 finally 中挂起。如果这样做,请使用 withContext(NonCancellable) NonCancellable documentation

相关问题