02/07/2023, 11:57 AM
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: Is there any way I could accomplish this or is this not possible by-design?

02/07/2023, 1:00 PM
Hrm… I see. If that’s the reason, then I’m dead in the water.

James Yox

02/07/2023, 4:08 PM
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:
val coroutineScope = ... // some coroutine scope

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

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


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