Skip to content

Instantly share code, notes, and snippets.

@pocesar
Last active July 29, 2019 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocesar/04863eaf4859f913a2dfc429d4c34e00 to your computer and use it in GitHub Desktop.
Save pocesar/04863eaf4859f913a2dfc429d4c34e00 to your computer and use it in GitHub Desktop.
A debouncer helper in Kotlin with coroutines
import kotlinx.coroutines.*
class Debouncer<T>(private val millis: Long, val block: (T) -> Unit) {
private var job: Job? = null
fun run(param: T) {
job?.cancel()
job = GlobalScope.launch(Dispatchers.Main) {
delay(millis)
block(param)
}
}
}
// usage
val textDebouncer = Debouncer<String?>(300, ::myCallback)
// or Debouncer<String>(300) { val -> dostuff(val) }
fun myCallback(text: String?) {
// do your magic with "some more text"
}
textDebouncer.run("some")
textDebouncer.run("some more")
textDebouncer.run("some more text")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment