https://kotlinlang.org logo
Title
j

jossiwolf

04/30/2021, 6:02 PM
Say I have a Flow of Booleans and only want to emit when they flip, what is the proper way to do that? What am I looking for?
suspend fun Flow<Boolean>.flippedTo(value: Boolean, block: () -> Unit) {
    var previous: Boolean? = null
    collect { current ->
        if (previous == !value && current == value) {
            block()
        }
        previous = current
    }
}
boolFlow.flippedTo(false) {
    println("Flipped from true to false")
}
boolFlow.flippedTo(true) {
    println("Flipped from false to true")
}
j

Javier

04/30/2021, 6:07 PM
StateFlow is not enough?
b

baxter

04/30/2021, 6:07 PM
Maybe try
distinctUntilChanged
? Or that ☝️
1