Skip to content

Instantly share code, notes, and snippets.

@AliAzaz
Forked from chibatching/FlowThrottleDebounce.kt
Created October 22, 2021 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AliAzaz/49a486100dff1ed240305d2dae936b4f to your computer and use it in GitHub Desktop.
Save AliAzaz/49a486100dff1ed240305d2dae936b4f to your computer and use it in GitHub Desktop.
Throttle and Debounce on Flow Kotlin Coroutines
fun <T> Flow<T>.throttle(waitMillis: Int) = flow {
coroutineScope {
val context = coroutineContext
var nextMillis = 0L
var delayPost: Deferred<Unit>? = null
collect {
val current = SystemClock.uptimeMillis()
if (nextMillis < current) {
nextMillis = current + waitMillis
emit(it)
delayPost?.cancel()
} else {
val delayNext = nextMillis
delayPost?.cancel()
delayPost = async(Dispatchers.Default) {
delay(nextMillis - current)
if (delayNext == nextMillis) {
nextMillis = SystemClock.uptimeMillis() + waitMillis
withContext(context) {
emit(it)
}
}
}
}
}
}
}
fun <T> Flow<T>.debounce(waitMillis: Long) = flow {
coroutineScope {
val context = coroutineContext
var delayPost: Deferred<Unit>? = null
collect {
delayPost?.cancel()
delayPost = async(Dispatchers.Default) {
delay(waitMillis)
withContext(context) {
emit(it)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment