Sam
03/01/2024, 10:22 AMCoroutineScope(…)
requires a coroutineContext
argument. By default it creates its own Job()
. It will also use Dispatchers.Default
if I don't specify a dispatcher. So what other coroutine context would I actually want to pass? It feels strange to have to write CoroutineScope(EmptyCoroutineContext)
, not to mention misleading since the resulting scope will not have an empty coroutine context. And it's inconsistent with MainScope()
, which takes no arguments at all. 🤔Sam
03/01/2024, 10:25 AMCoroutineScope(…)
defaults to make a Job()
while MainScope()
makes a SupervisorJob()
. I'm not sure why those are different.renatomrcosta
03/01/2024, 10:26 AMSam
03/01/2024, 10:28 AMcoroutineScope { … }
or just launch { … }
. As I understand it, CoroutineScope(…)
is primarily intended for top-level scopes, so there'd be nothing to inherit. I take your point about the coroutine name and other context options. With MainScope()
we're encouraged to pass those using MainScope() + context
. So there's still a disparity.renatomrcosta
03/01/2024, 10:28 AMSam
03/01/2024, 10:29 AMrenatomrcosta
03/01/2024, 10:30 AMSam
03/01/2024, 10:47 AMMainScope()
should be different from that of `CoroutineScope(…)`—besides the dispatcher, I mean—or would be less likely to need customization? Did I understand you right that you think MainScope()
is more likely to be used solely as a "top-level" scope, while CoroutineScope(…)
could be appropriate for a wider range of situations? That doesn't quite tally with my own understanding—I see them both as top-level scope builders—but I'm certainly interested in other points of view.CLOVIS
03/01/2024, 1:17 PMCoroutineScope()
you can convert it back into a scope.streetsofboston
03/01/2024, 1:22 PMJeff Lockhart
03/01/2024, 4:20 PMsometimes you have access to a coroutine context, but not its scope, so you can't launch stuff into it. Using CoroutineScope() you can convert it back into a scope.
Roman discourages wrapping a
suspend
function's CoroutineContext
in a new CoroutineScope
instance, but to make the function's behavior clear, rather:
If you need to launch a coroutine that keeps running after your function returns, then make your function an extension ofor passCoroutineScope
as parameter to make your intent clear in your function signature. Do not make these functions suspending.scope: CoroutineScope
bezrukov
03/01/2024, 4:21 PMCoroutineScope(…)
is primarily intended for top-level scopes, so there'd be nothing to inherit.
Sometimes you have to use CoroutineScope, but still create parent-child relation:
val parentScope = CoroutineScope(....) // initialized somewhere
val componentScope = CoroutineScope(Job(parentScope.coroutineContext.job))