I use the WorkManager version 2.2.0 to start a Coroutines API Call when the user gets online again.
In the example by Google, if I want to change the Thread of my CoroutineWorker from the default (Dispatchers.Default
) to Dispatchers.IO
, then I simply have to override the val
coroutineContext
such as:
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
}
}
But Android Studio and the Docs tell me, that overriding coroutineContext
is deprecated:
What am I missing and how can I resolve this issue?
The answer to your question is in release notes:
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
Also there's an answer in sources:
/**
* 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
So you could do the following:
override suspend fun doWork(): Result = withContext(Dispatchers.IO) { ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With