Is there any fancy way to implement debounce
logic with Kotlin Android?
I\'m not using Rx in project.
There is a way in Java, but it is too big
A more simple and generic solution is to use a function that returns a function that does the debounce logic, and store that in a val.
fun debounce(delayMs: Long = 500L,
coroutineContext: CoroutineContext,
f: (T) -> Unit): (T) -> Unit {
var debounceJob: Job? = null
return { param: T ->
if (debounceJob?.isCompleted != false) {
debounceJob = CoroutineScope(coroutineContext).launch {
delay(delayMs)
f(param)
}
}
}
}
Now it can be used with:
val handleClickEventsDebounced = debounce(500, coroutineContext) {
doStuff()
}
fun initViews() {
myButton.setOnClickListener { handleClickEventsDebounced(Unit) }
}