How to Implement Debounce Using Coroutines?
Learn how to handle rapid events gracefully in Kotlin with Coroutines.
If you’re preparing for a Kotlin or Android interview, you might encounter this question: How would you implement a debounce mechanism in Kotlin?
Let’s first understand debounce in simple words: Debounce is like a wait-and-see rule for your app.
Imagine you are typing in a search box, and every letter you type sends a request to the server. If you type quickly, the server could get flooded with requests.
With debounce, the app waits for a short pause (say 300ms) after your last action before doing anything. If you type another letter before the wait is over, the previous action is canceled, and the timer starts again.
So, in one line, we can say: Debounce ensures that an action happens only after things have settled down, ignoring rapid repeated triggers.
Now, let’s implement debounce using the Kotlin Coroutines.
class Debouncer(private val scope: CoroutineScope, private val waitTime: Long) {
    private var job: Job? = null
    fun post(block: () -> Unit) {
        // Cancel the previous scheduled task if any
        job?.cancel()
        
        // Schedule a new task after the delay
        job = scope.launch {
            delay(waitTime)
            block()
        }
    }
}Let’s try to understand the above code.
- scope: A CoroutineScope to launch coroutines. 
- job: Holds the current pending task, so we can cancel it if needed. 
- post(): Cancels the previous job and schedules a new one after waitTime. 
Example usage:
fun main() = runBlocking {
    val debouncer = Debouncer(scope = this, waitTime = 300L)
    
    debouncer.post { println(”Outcome School 1”) }
    delay(100)
    debouncer.post { println(”Outcome School 2”) }
    delay(400)
    debouncer.post { println(”Outcome School 3”) }
    delay(200)
    debouncer.post { println(”Outcome School 4”) }
    delay(500)
}Output:
Outcome School 2
Outcome School 4Explanation:
- “Outcome School 1” is canceled by “Outcome School 2” within 300ms. 
- “Outcome School 2” executes because no new post happens within 300ms. 
- “Outcome School 3” is canceled by “Outcome School 4”. 
- “Outcome School 4” finally executes. 
This is how you can implement Debounce Using Coroutines.
Prepare for your Android Interview: Android Interview Questions and Answers
Thanks
Amit Shekhar
Founder, Outcome School


