Created
November 17, 2024 03:52
-
-
Save Wavesonics/85bbf8ae6474860fd421c8262b93a8ef to your computer and use it in GitHub Desktop.
Debounce a Flow's emissions until it is quite for some period
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
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