https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

samuel

11/23/2020, 12:41 PM
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

flosch

11/23/2020, 1:08 PM
Copy code
fun <T> Flow<T>.fireAndForget(
    block: (T) -> Unit
): Flow<T> = onEach { emission -> runCatching { block(emission) } }
should do the trick
🙏 1
s

samuel

11/23/2020, 1:11 PM
thank you @flosch that looks very nice 🙏
b

bezrukov

11/23/2020, 1:57 PM
onEach
doesn't collect anything, you still have to run
launchIn(someScope)
after it
s

samuel

11/23/2020, 2:13 PM
@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

bezrukov

11/23/2020, 2:14 PM
yes, that's correct if it is intermediate step. In your initial snippet, it was terminal operator
s

samuel

11/23/2020, 2:17 PM
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
2 Views