https://kotlinlang.org logo
Title
l

Lukas Lechner

08/12/2022, 10:00 AM
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

simon.vergauwen

08/12/2022, 10:01 AM
You can do
flow { coroutineScope { } }
. The only thing that is forbidden is
emit
from a different Coroutine, but following is valid.
flow {
  coroutineScope {
    launch { /** do something */ }
    while(true) {
      currentCoroutineContext().ensureActive()
      emit(1)
    }
  }
}
j

Joffrey

08/12/2022, 10:07 AM
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

Lukas Lechner

08/12/2022, 10:16 AM
@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

Nick Allen

08/15/2022, 7:21 PM
Snippet above should work for your use case. Maybe you are emitting after the
coroutineScope
instead of inside it?