当用户再次上线时,我使用WorkManager 2.2.0版启动Coroutines 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
:我缺少什么?如何解决此问题?
最佳答案
您的问题的答案在发行说明中:
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) { ...