Last active
February 18, 2025 15:19
-
-
Save tlux/765ad4893b00d015e46a89d354a82db4 to your computer and use it in GitHub Desktop.
Kotlin Flow Dedup Extension Functions
This file contains hidden or 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
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