Is there a proper way to "merge" multiple jobs fro...
# coroutines
t
Is there a proper way to "merge" multiple jobs from flow
launchIn
to allow simple cancellation without cancelling the scope / job that is used in the
launchIn
call? Currently saving each jobs separately and cancelling them one by one.
t
Perhaps
scope.coroutineContext.cancelChildren()
would work for you?
t
Unfortunately no there's other things running in that scope 😞 Found https://github.com/Kotlin/kotlinx.coroutines/issues/1001#issuecomment-478337694 seems a little like my need. I guess I'll keep keeping job references and cancel them one by one.
t
You could create a new scope under the current scope and launch your jobs within that new child scope, to segregate the jobs you want to cancel.
t
That's what I thought first but https://kotlinlang.org/docs/reference/coroutines/basics.html#scope-builder / https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html implies that the scope is more or less blocking so would not fit ? Or I'm missing something obvious
b
You can create child scope as: val childScope = scope + Job(scope.coroutineContext.job) Then just use launchIn(childScope)
☝️ 1
t
Got error on the + None of the following candidates is applicable because of receiver type mismatch:
Ok stupid IDE bug that imported the wrong one thanks will test this.
g
coroutineSvope is not blocking, it's suspend
Could you show some sample code, what is your use case creating one more nested scope
Because creating scope as Denis showed above will solve your case, but it breaks structured concurrency, you have to manage lifecycle of one more scope
b
I've run into a case like this as well, is there a way to create a child scope manually that doesn't break structured concurrency? I had a case where I wanted a child scope but didn't want the semantics of
coroutineScope
or
supervisorScope
t
The code is simple I have a global state manager that have it's own scope and can be cancelled when disposed. That state manager can connect to different other things and will collect some state flows. When the state manager wants to connect to a different thing, it need to stop collecting from the first then collect on the new one. So I need to cancel a group of collect from a scope that is different a child of the main one. The proposed solution does work perfectly for my need with a SupervisorJob I can cancelChildren and collect again.