I am writing a custom flow and inside it I want to...
# coroutines
d
I am writing a custom flow and inside it I want to non-blocking collect some other flow, process it's emissions and emit them:
Copy code
val externalFlow = flowOf(1,3,4)
val myFlow = flow<Int> {
  coroutineScope { externalFlow.collect { this@flow.emit(it + 8) } }
  emit(1)
  emit(99)
}
I've used
coroutineScope
, but I'm worried that it won't be cancelled when
myFlow
collection is cancelled or interrupted. It's just that I've found internal
flowScope
builder in
coroutines.core
and it says:
Copy code
This builder is similar to coroutineScope with the only exception that it ties lifecycle of children and itself regarding the cancellation, thus being cancelled when one of the children becomes cancelled.
Can I achieve similar effect for my case? Or using
coroutineScope
like I did is ok?
ah, wait this still blocks until
externalFlow
finishes emissions 😞 I want something with the semantics: collect external flow just in case it will emit something, then emit this too, otherwise just emit my own stuff.
Solved this by using
merge
instead of collecting external flow inside
flow {}
j
If you want concurrent emissions you could also use the
channelFlow
builder, which allows you to start coroutines inside and send to the flow's channel concurrently
d
Thank you! I had a glimpse of memory of something like this existing, but couldn't remember its name.