Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active July 31, 2024 22:57
Show Gist options
  • Save tlux/765ad4893b00d015e46a89d354a82db4 to your computer and use it in GitHub Desktop.
Save tlux/765ad4893b00d015e46a89d354a82db4 to your computer and use it in GitHub Desktop.
Kotlin Flow Dedup Extension Functions
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