https://kotlinlang.org logo
#flow
Title
# flow
a

Alexander Maryanovsky

03/24/2022, 6:22 PM
Is there a way to explicitly create a child coroutine scope? My use case is that I want to create a bunch of `SharedFlow`s and occasionally close them all. The way I’m trying to do that is by creating them with
shareIn(scope.newChildScope())
and closing with
scope.coroutineContext.cancelChildren()
Hmm, or maybe I don’t need to create a child. Seems that
shareIn
actually launches a child and the flow runs in it.
d

DALDEI

06/10/2022, 5:06 AM
I think this does it, I've been using the following to create a 'module' scope. You can use Job() I think instead of SupervisorJob -- SupervisorJob has the semantics that makes sense for my uses.
fun ManagerScope(parent: CoroutineScope,
dispatcher: CoroutineDispatcher) : CoroutineScope = CoroutineScope( dispatcher + SupervisorJob(parent.coroutineContext[Job]) )
And yes shareIn runs a child coroutine, but you dont get a reference to it directly. Its lifecycle is controled by the sharing parameter
Rereading shareIn and launchIn, I think this is closer to what you want suspend fun doflow() { coroutineScope { val sflow = .... flow producing ... .shareIn( this ) ... val consume = sflow.launchIn( this ) .... // to totally cancel the flow this.cancel() } I havent tried the above, to my read of the docs it would work
4 Views