Hello folks, I have a case where I’m collecting a ...
# coroutines
a
Hello folks, I have a case where I’m collecting a flow to do some operations but on every emission I need to do a side effect and have another different flow to observe until there’s a new value emitted. I was thinking on using flatMapLatest but that would multiply the initial emission every time the internal one emits something + would get delayed, so I though about doing a
onEachLatest
sort of 🤔 Sharing here for feedback or in case I’m missing something 😬
Copy code
@ExperimentalCoroutinesApi
public fun <T> Flow<T>.onEachLatest(action: suspend (T) -> Unit): Flow<T> = transformLatest { value ->
    action(value)
    return@transformLatest emit(value)
}
the only real difference with
onEach
is the
transform
->
transformLatest
but I guess that should work, right?
n
Simpler:
mapLatest { action(it); it }
Avoid side effects unless you are calling a terminal operator. If a
Flow
is collected twice, your side effects will happen twice. If you are calling a terminal operator, then consider just using
collectLatest
and do your side effect there.
🙏 1
👍 1
a
thank you @Nick Allen I’ll look into that