Last active
July 31, 2024 22:57
-
-
Save tlux/765ad4893b00d015e46a89d354a82db4 to your computer and use it in GitHub Desktop.
Kotlin Flow Dedup Extension Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.flow.flow | |
inline fun <T> Flow<T>.dedupBy(crossinline predicate: suspend (T, T) -> Boolean): Flow<T> = | |
let { source -> | |
var prevValue: T? = null | |
flow { | |
source.collect { value -> | |
if (prevValue == null || !predicate(prevValue!!, value)) { | |
prevValue = value | |
emit(value) | |
} | |
} | |
} | |
} | |
fun <T> Flow<T>.dedup(): Flow<T> = dedupBy { a, b -> a == b } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment