Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WorkManager - CoroutineWorker: Overriding coroutineContext is deprecated

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?

like image 745
Paul Spiesberger Avatar asked Nov 20 '19 16:11

Paul Spiesberger


1 Answers

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

like image 124
Vitalii Malyi Avatar answered Oct 29 '22 22:10

Vitalii Malyi