https://kotlinlang.org logo
Title
z

zak.taccardi

09/10/2020, 8:05 PM
Given a
CoroutineScope
, what is the idiomatic way to create a child scope?
w

wasyl

09/10/2020, 8:06 PM
I suppose it’s
coroutineScope { }
z

zak.taccardi

09/10/2020, 8:08 PM
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
val globalSdkScope: CoroutineScope

val childScope = globalSdkScope + Job(globalSdkScope.coroutineContext[Job]!!)
2
c

Casey Brooks

09/10/2020, 8:18 PM
I think you’re looking for a SupervisorScope rather than a normal CoroutineScope
z

zak.taccardi

09/10/2020, 8:18 PM
why? I would want a failure with the child to fail the parent
cancelling a child won’t cancel the parent right?
c

Casey Brooks

09/10/2020, 8:21 PM
Yeah you’re right. But it also sounds weird to have a “global” context cancelled when a child does (from your snippet)
z

zak.taccardi

09/10/2020, 8:21 PM
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

Zach Klippenstein (he/him) [MOD]

09/10/2020, 8:45 PM
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

zak.taccardi

09/10/2020, 8:46 PM
already did! haha
I’m using these two functions as a workaround for now
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

gildor

09/10/2020, 11:53 PM
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

zak.taccardi

10/06/2020, 10:18 PM
GlobalScope
should never be used, though
g

gildor

10/06/2020, 11:35 PM
It's an overstatement