Android WorkManager - CoroutineWorker:覆盖coroutineContext已过时。

6
我使用 WorkManager 版本 2.2.0 在用户重新联网时启动协程 API 调用。
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和文档告诉我,覆盖coroutineContext已经被弃用:

enter image description here

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

6
你的问题答案在版本说明中:

弃用CoroutineWorker.coroutineContext。该字段错误地被类型化为 CoroutineDispatcher;您不再需要它,因为您可以自己在挂起函数的函数体中访问所需的coroutineContext。

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) { ...


谢谢您的回答,但我如何在挂起函数的主体中转到所需的coroutineContext - Paul Spiesberger
1
@Spipau 只需将 coroutineScope 替换为 withContext(Dispatchers.IO) 或您需要的任何其他调度程序 - Vitalii Malyi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接