Skip to content

Instantly share code, notes, and snippets.

@gbajaj
Created July 1, 2025 21:22
Show Gist options
  • Save gbajaj/1acfb63f3095e21490cee94eef2d9bda to your computer and use it in GitHub Desktop.
Save gbajaj/1acfb63f3095e21490cee94eef2d9bda to your computer and use it in GitHub Desktop.
Debounce implementation
import kotlinx.coroutines.*
class Debouncer(private val delayMs: Long = 300) {
private var debounceJob: Job? = null
fun submit(scope: CoroutineScope, action: () -> Unit) {
debounceJob?.cancel()
debounceJob = scope.launch {
delay(delayMs)
action()
}
}
}
/**---------Usage----------**/
val debouncer = Debouncer(500)
fun onTextChanged(newText: String) {
debouncer.submit(CoroutineScope(Dispatchers.Main)) {
performSearch(newText)
}
}
/**-------- Debouncing with out debouncer; directly using on a click listener ***/
fun View.setDebouncedClickListener(intervalMs: Long = 600, onClick: (View) -> Unit) {
var lastClickTime = 0L
setOnClickListener {
val currentTime = System.currentTimeMillis()
if (currentTime - lastClickTime >= intervalMs) {
lastClickTime = currentTime
onClick(it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment