egek
10/14/2021, 1:45 PMKlitos Kyriacou
10/14/2021, 2:14 PMGrégory Lureau
10/15/2021, 7:14 AMclass Debouncer(private val timeProvider: TimeProvider, private val durationMs: Long) {
private var lastTimestamp: Long = Long.MIN_VALUE
fun throttleFirst(block: () -> Unit) {
val now = timeProvider.nowMs() // You could also remove the TimeProvider and just call System.currentTimeMillis(), just a bit easier to unit-test that way
if (lastTimestamp + durationMs < now) {
block()
lastTimestamp = now
}
}
}
You don't really need a lib for something that simple IMO, and to use it
class MyClass {
private val uiDebouncer = Debouncer(...)
fun onUiClicked() {
uiDebouncer.throttleFirst {
doHeavyStuff()
}
}
}
I mean there is tons of libs like Guava, Rx and more that will adds a lot of functionnalities, but that's not super complex to write and adding a library means being dependent, choose wisely 😉