Android WorkManager - CoroutineWorker:不推荐覆盖 coroutineContext

Android WorkManager - CoroutineWorker: Overriding coroutineContext is deprecated

我使用WorkManager版本2.2.0启动一个协程API当用户再次上线时调用

In the example by Google,如果我想将 CoroutineWorker 的线程从默认值 (Dispatchers.Default) 更改为 Dispatchers.IO,那么我只需覆盖 val coroutineContext 如:

class CoroutineDownloadWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {

    override val coroutineContext = Dispatchers.IO

    override suspend fun doWork(): Result = coroutineScope {
         // do some work here and return a Result
    }
}

但是 Android Studio 和 the Docs 告诉我,覆盖 coroutineContext 已被弃用:

我错过了什么,我该如何解决这个问题?

您问题的答案在发行说明中:

Deprecated CoroutineWorker.coroutineContext. This field was incorrectly typed as a CoroutineDispatcher; you should no longer need it as you can go to the desired coroutineContext yourself in the body of the suspending function.

https://developer.android.com/jetpack/androidx/releases/work#2.1.0-alpha01

来源中也有答案:

/**
 * The coroutine context on which [doWork] will run. By default, this is [Dispatchers.Default].
 */
@Deprecated(message = "use withContext(...) inside doWork() instead.")
open val coroutineContext = Dispatchers.Default

因此您可以执行以下操作:

override suspend fun doWork(): Result = withContext(Dispatchers.IO) { ...