Last active
July 12, 2022 21:38
-
-
Save josebraz/8cc302511d8b240400f6e6f594417766 to your computer and use it in GitHub Desktop.
Debounce
This file contains 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
open class Debouncer<T>( | |
protected val scope: CoroutineScope, | |
protected val period: Long | |
) { | |
protected var scheduleJob: Job? = null | |
protected var lastRan: Long = -period | |
fun debounce( | |
arg: T, | |
block: suspend CoroutineScope.(T) -> Unit | |
): Boolean = debounce(arg, period, block) | |
protected fun debounce( | |
arg: T, | |
delay: Long, | |
block: suspend CoroutineScope.(T) -> Unit | |
): Boolean { | |
synchronized(this@Debouncer) { | |
scheduleJob?.cancel() | |
scheduleJob = scope.launch { | |
delay(delay) | |
synchronized(this@Debouncer) { | |
scheduleJob = null | |
lastRan = System.currentTimeMillis() | |
} | |
block(arg) | |
} | |
} | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment