gpt4 book ai didi

Android WorkManager - CoroutineWorker : Overriding coroutineContext is deprecated

转载 作者:行者123 更新时间:2023-12-02 14:24:54 29 4
gpt4 key购买 nike

我使用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 已被弃用:

enter image description here

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

最佳答案

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

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

所以你可以执行以下操作:

覆盖挂起乐趣 doWork(): Result = withContext(Dispatchers.IO) { ...

关于Android WorkManager - CoroutineWorker : Overriding coroutineContext is deprecated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58958618/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com