I want to call a method that makes an API call which is triggered by user interaction but I want to prevent it to get called multiple times if it hasn't been 1 minute yet, what would be the best way to do this?
k
Klitos Kyriacou
10/14/2021, 2:14 PM
In Java, you could use RateLimiter from Guava (similar utilities are also available in some other libraries). You can use it in Kotlin too, but I don't know of any existing Kotlin-specific ones, especially any that play nicely with coroutines.
class 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
Copy code
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 đŸ˜‰