Is there a flow operator which allows me to to tak...
# flow
e
Is there a flow operator which allows me to to take the last two events and map them? or do I need to use a SharedFlow/StateFlow for that?
w
You can use a top-level
combine
for that, or
flowA.combine(flowB) { }
e
But I only have one flow here. So there is no flowA or B only A.
w
ah, the last two events of the same flow 🤔
combine(flowA, flowA.drop(1))
? Although it would seem useful to have a shared flow to not trigger the collection twice
e
If it was a regular list I think
fold/reduce
would make sense.
So whenever FlowA is updated I want to fold the last two values.
A shared flow with a buffer of 2 ought to work, but ideally a regular flow would work
w
Yeah I wanted to suggest looking into fold/reduce too. I found something like this in our codebase too:
Copy code
fun <T> Flow<T>.zipWithPreviousOrNull() = flow {
    var prev: T? = null
    collect { value ->
        emit(prev to value)
        prev = value
    }
}
but I can’t say if it’s the best solution
e
Yeah, I was thinking about writing my own. It just feels like there should be an operator for this already hehe
e
e
Thanks for all the help! It answers my all my questions 🙂
s
Similarly to the code snippet above, we’ve been using this in our code base https://github.com/HedvigInsurance/android/blob/e2b5df0684487465922a57305abcc2efc0[…]/main/java/com/hedvig/app/util/coroutines/HistoryOfLastValue.kt and it’s been working perfectly fine 😄