https://kotlinlang.org logo
Title
j

Jan

03/03/2020, 2:30 PM
kind of android related, but which coroutine scope would you use in background services? e.g. intent services or job services?
e

Evan R.

03/03/2020, 2:31 PM
As long as it’s not reading files or anything I’d use
Dispatchers.Default
j

Jan

03/03/2020, 2:32 PM
that's the context but how would you launch them?
s

streetsofboston

03/03/2020, 2:34 PM
val scope = CoroutineScope(Dispatcthers.Default + SuperVisorJob())

scope.launch { .... }
👍 1
j

Jan

03/03/2020, 2:34 PM
thanks 🙂
a

Adam Powell

03/03/2020, 2:59 PM
CoroutineWorker
with WorkManager
3
just creating a new scope like the above doesn't include when to cancel it for cleanup or otherwise manage lifecycle along with Android; CoroutineWorker does this for you
and WorkManager is a lot more compatible and robust across Android versions than working with IntentService or JobService directly
2
s

Saket Poddar

03/05/2020, 9:15 AM
Agreed with @Adam Powell with above implementation you will have to manage your coroutineScope to cancel. Better use WorkManager where you can return results as well.
d

dave08

03/06/2020, 3:49 AM
Just beware of unique work, for some reason it could get stuck... if you return failed for sure, but even if not, sometimes I have some works that stay blocked and just don't run until all works get purged.
Whereas IntentService just queued them, and keeps running them even if previous ones fail.