Skip to content

Instantly share code, notes, and snippets.

@Wavesonics
Created November 17, 2024 03:52
Show Gist options
  • Save Wavesonics/85bbf8ae6474860fd421c8262b93a8ef to your computer and use it in GitHub Desktop.
Save Wavesonics/85bbf8ae6474860fd421c8262b93a8ef to your computer and use it in GitHub Desktop.
Debounce a Flow's emissions until it is quite for some period
fun <T> Flow<T>.debounceUntilQuiescent(duration: Duration): Flow<T> = channelFlow {
var job: Job? = null
collect { value ->
job?.cancel()
job = launch {
delay(duration)
send(value)
job = null
}
}
}
fun <T> Flow<T>.debounceUntilQuiescentBy(by: (T) -> Any, duration: Duration): Flow<T> = channelFlow {
val jobs = mutableMapOf<Any, Job>()
collect { value ->
val id = by(value)
jobs[id]?.cancel()
jobs[id] = launch {
delay(duration)
send(value)
jobs.remove(id)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment