Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Kotlin Coroutine Debouncer
class CoroutineDebouncer<K, V> constructor(
private val pendingBoard: ConcurrentMap<K, Deferred<V?>>
) {
* Debounce given a `task` based upon given `id`. This prevents jobs with same IDs run in parallel.
* For subsequent callers get Deferred<V> of first (winning) coroutine.
* Once Deferred<V> completes it is remove from the board.
* @param id for uniquely identifying a task
* @param context under which given coroutine will be executed
* @param task to execute if there isn't already a task with given `id`
* @return Deferred<V> created by scheduled `task` or an existing Deferred<V> from previous coroutines
suspend fun debounce(id: K, context: CoroutineContext, task: suspend () -> V?): Deferred<V?> {
return pendingBoard.computeIfAbsent(id) {
async (context, start = CoroutineStart.LAZY) {
} finally {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment