Android WorkManager - CoroutineWorker: Overriding coroutineContext is deprecated
Asked Answered
B

1

6

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:

enter image description here

What am I missing and how can I resolve this issue?

Borodin answered 20/11, 2019 at 16:2 Comment(0)
S
6

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

Subclinical answered 20/11, 2019 at 16:14 Comment(2)
Thanks for the answer, but how do I go to the desired coroutineContext in the body of the suspending function?Borodin
@Spipau just replace coroutineScope with withContext(Dispatchers.IO) or any other dispatcher you needSubclinical

© 2022 - 2024 — McMap. All rights reserved.