Is it possible to start a Coroutine in a flow oper...
# coroutines
l
Is it possible to start a Coroutine in a flow operator, so that when the flow completes, the Coroutine is cancelled as well? I somehow need access to the scope of the flow, right?
s
You can do
flow { coroutineScope { } }
. The only thing that is forbidden is
emit
from a different Coroutine, but following is valid.
Copy code
flow {
  coroutineScope {
    launch { /** do something */ }
    while(true) {
      currentCoroutineContext().ensureActive()
      emit(1)
    }
  }
}
j
What is your use case, actually? You might better be served by
callbackFlow
(or maybe
channelFlow
) depending on what you're trying to do
l
@simon.vergauwen Oh, its actually that simple 🙂 Thanks
Okay, with
coroutineScope
, the flow suspends until the launched Coroutine has completed. How can I create a Coroutine that runs concurrently with the flow?
@Joffrey My use case is that whenever someone collects from a flow that is exposed from a repository, I want to start a Coroutine that fetches data from the network and stores it in the database. The flow of the repository should emit the items that the database flow (Android Room Database) emits. So it basically should just forward the emissions from the database and also start/stop the process of updating the database on subscription/unsubscription.
n
Snippet above should work for your use case. Maybe you are emitting after the
coroutineScope
instead of inside it?