Given a `CoroutineScope`, what is the idiomatic wa...
# coroutines
z
Given a
CoroutineScope
, what is the idiomatic way to create a child scope?
w
I suppose it’s
coroutineScope { }
z
I’m not in a suspending content
I would need to implement:
(CoroutineScope) -> CoroutineScope
where the output is a child scope
maybe a better question is a child job
This is just a terrible API lol
Copy code
val globalSdkScope: CoroutineScope

val childScope = globalSdkScope + Job(globalSdkScope.coroutineContext[Job]!!)
2
c
I think you’re looking for a SupervisorScope rather than a normal CoroutineScope
z
why? I would want a failure with the child to fail the parent
cancelling a child won’t cancel the parent right?
c
Yeah you’re right. But it also sounds weird to have a “global” context cancelled when a child does (from your snippet)
z
when a child does what?
the parent would only fail if the child fails
if the child is cancelled normally then the parent would still be active
z
The API is very bad, I agree. I filed an issue about this a year ago, if you wanna 👍: https://github.com/Kotlin/kotlinx.coroutines/issues/1485
z
already did! haha
I’m using these two functions as a workaround for now
Copy code
public fun CoroutineScope.newChildScope(
    context: CoroutineContext = EmptyCoroutineContext
): CoroutineScope {
    val parentScope = this

    return parentScope + parentScope.job.newChildJob() + context
}

public fun Job.newChildJob(): Job {
    val parentJob = this

    return Job(parent = parentJob)
}
g
Just curious, what is your use case for this? I think it doesn't have any helper functions because it low level staff which useful for library authors rather than for end users For example your snippet will crash when you try to get Job from GlobalScope, so it's up to you decide how this function should behave in this case
z
GlobalScope
should never be used, though
g
It's an overstatement