Throttle and Debounce on Flow Kotlin Coroutines
This file contains 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>.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
Why you used Dispatchers.Default in line 16?
I know that if you don't add this dispacher, code will crash due to IllegalStateException
but I can't figure out how Dispatchers.Default fix that problem