Hi, I have a flow of integers. I'd like to keep tr...
# flow
t
Hi, I have a flow of integers. I'd like to keep track of the highest value received and perform an action if a received value is greater than the highest. I'm struggling to figure out which operation I can use to do that https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/ - any ideas? Equivalent without flows might be something like:
Copy code
var highest = 0
for (i in myIntegers) {
   if (i > highest) {
      highest = i
      doSomethingElse()
   }
}
Turns out
scan
is what I was looking for 🙂
Copy code
data class State(val max: Int)

    val l = flowOf(1,3,2,5,4,3,6,2,3)
            .scan(State(0)) { state, value ->
                // Do something fun with max here
                State(maxOf(state.max, value))
            }
... or while preserving the original flow...
Copy code
data class State(val max: Int, val value: Int)

    val l = flowOf(1,3,2,5,4,3,6,2,3)
            .scan(State(0, 0)) { state, value ->
                // Do something fun with max here
                State(maxOf(state.max, value), value)
            }
            .drop(1)
            .map { it.value }
e
You could have just wrapped your original code into a flow:
Copy code
flow { 
    var highest = 0
    collect { i ->
       if (i > highest) {
          highest = i
          doSomethingElse()
       }
       emit(i) // emit original i
    }
}
t
True, it's good to have an option not to use mutable state though 👍