i am curious if there is a better way to run a “fi...
# coroutines
s
i am curious if there is a better way to run a “fireAndForget” action on the items in a flow as an intermediary step e.g in a repository
Copy code
suspend inline fun <T>Flow<T>.fireAndForget(crossinline block: (T) -> Unit): Flow<T> {
    coroutineScope {
        launch {
            runCatching {
                collect {
                    block(it)
                }
            }
        }
    }
    return this
}
f
Copy code
fun <T> Flow<T>.fireAndForget(
    block: (T) -> Unit
): Flow<T> = onEach { emission -> runCatching { block(emission) } }
should do the trick
🙏 1
s
thank you @flosch that looks very nice 🙏
b
onEach
doesn't collect anything, you still have to run
launchIn(someScope)
after it
s
@bezrukov looking at the source of
onEach
it runs
unsafeTransform
which collects the flow and applies the given transformation, so
launchIn
is not necessary especially if this extension is run as an intermediary step (before the flow is emitted downstream)
b
yes, that's correct if it is intermediate step. In your initial snippet, it was terminal operator
s
yes it was a terminal “fireAndForget” action, i got away with it by returning the initial flow, but i much prefer the snippet by florian