I was under the impression that a shared flow’s ch...
# flow
d
I was under the impression that a shared flow’s child flows are completed if the parent scope gets canceled, but apparently the only thing that happens is that the parent emissions end, but the child flows are happily collecting nothing, i.e. are not completed. (Small example here: https://gist.github.com/realdadfish/63773e600d0bebb36ce3d078978c02b4) Is there any way I could accomplish this or is this not possible by-design?
d
Hrm… I see. If that’s the reason, then I’m dead in the water.
j
You could ensure that the coroutine scope used for the parent flow (the shared one) is the parent scope of the child used for collection. That way, when the shared flow has its scope cancelled, you ensure that collection also stops. Basically treat this as a structured concurrency problem and not a flow specific problem. For instance:
Copy code
val coroutineScope = ... // some coroutine scope

val flow = otherFlow.shareIn(coroutineScope, SharingStarted.Eagerly)

coroutineScope.launch {
  flow.collect { ... }
}

delay(3.seconds)

// This would cancel both sharing and collection since collect is in a child scope of coroutineScope.
coroutineScope.cancel()