On Android, what CoroutineContext would y’all use ...
# coroutines
s
On Android, what CoroutineContext would y’all use for a fire-and-forget network request where the app doesn’t care about the response? Is this a valid case for
GlobalScope.launch { ... }
?
👍 1
l
GlobalScope.launch(Dispatchers.Main)
if I have to be in-sync with stuff on main thread
Or I use this scope:
val AppProcessScope = CoroutineScope(Dispatchers.Main)
But I tend to avoid non cancellable scopes and tie them to a lifecycle, or cancel them at some point based on other things.
2
s
Gotcha, thanks. This is just an HTTP post call that has no bearing on the UI
l
Can you tell what is its purpose?
j
I would recommend something like what Louis suggested. Having explicit control will prove to be valuable with little upfront investment. Personally, I use an AppScope and UserSessionScope.
👍 1
s
@louiscad I’m just throwing a piece of data at the server for it to store. I don’t want it to be cancelled if the user leaves the screen, so I’d like for it to be tied to the application scope. An AppScope or UserSessionScope would be perfect for this, but it’d be a large investment to implement in our project
l
@Seri I'd use WorkManager for this kind of thing to handle failures and retries correctly. The ktx artifact integrates nicely with coroutines.
s
Nice! I’ll take a look
t
Or I use this scope:
val AppProcessScope = CoroutineScope(Dispatchers.Main)
@louiscad I assume you put this in your Android Application class? What is the benefit using this over the already provided
GlobalScope
?
l
@Thomas I'd put it anywhere. GlobalScope doesn't specify a dispatcher, so it defaults to the multithreaded
Dispatchers.Default
.
👍 1