Android WorkManager-CoroutineWorker:不建议使用覆盖coroutineContext

时间:2019-11-20 16:02:59

标签: android android-architecture-components android-jetpack android-workmanager

当用户再次上线时,我使用WorkManager 2.2.0版启动Coroutines API调用。

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

coroutineContext

但是Android Studio和the Docs告诉我,不赞成使用覆盖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 } }

enter image description here

我缺少什么?如何解决此问题?

1 个答案:

答案 0 :(得分:2)

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

  

不推荐使用的CoroutineWorker.coroutineContext。这个领域是   错误地键入为CoroutineDispatcher;你应该不再需要   因为您可以自己进入体内所需的协程   暂停功能。

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