Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active February 18, 2025 15:19
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
package io.redigital.rebased.ext.flow
import arrow.core.None
import arrow.core.Option
import arrow.core.some
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.transform
fun <T> Flow<T>.dedup(): Flow<T> = dedupBy { it }
inline fun <T, U> Flow<T>.dedupBy(crossinline mapper: suspend (T) -> U): Flow<T> =
dedupWith { prev, current -> mapper(prev) == mapper(current) }
inline fun <T> Flow<T>.dedupWith(crossinline equal: suspend (T, T) -> Boolean): Flow<T> = let {
var prev: Option<T> = None
transform { value ->
if (prev.isNone() || prev.isSome { !equal(it, value) }) {
emit(value)
prev = value.some()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment