https://kotlinlang.org logo
#flow
Title
# flow
e

enighma

04/14/2022, 9:05 AM
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

wasyl

04/14/2022, 9:51 AM
You can use a top-level
combine
for that, or
flowA.combine(flowB) { }
e

enighma

04/14/2022, 9:54 AM
But I only have one flow here. So there is no flowA or B only A.
w

wasyl

04/14/2022, 10:01 AM
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

enighma

04/14/2022, 10:02 AM
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

wasyl

04/14/2022, 10:03 AM
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

enighma

04/14/2022, 10:04 AM
Yeah, I was thinking about writing my own. It just feels like there should be an operator for this already hehe
e

ephemient

04/14/2022, 10:51 AM
e

enighma

04/14/2022, 11:50 AM
Thanks for all the help! It answers my all my questions 🙂
s

Stylianos Gakis

04/28/2022, 8:54 AM
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 😄
6 Views