Created
July 1, 2025 21:22
-
-
Save gbajaj/1acfb63f3095e21490cee94eef2d9bda to your computer and use it in GitHub Desktop.
Debounce implementation
This file contains hidden or 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
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