Skip to content

Instantly share code, notes, and snippets.

@addeeandra
Created January 27, 2021 02:24
Show Gist options
  • Save addeeandra/f143f224d8328c3c28ddab9f8cae6244 to your computer and use it in GitHub Desktop.
Save addeeandra/f143f224d8328c3c28ddab9f8cae6244 to your computer and use it in GitHub Desktop.
Debounce wrapper for LiveData observer
class Debounce<T>(
val data: LiveData<T>,
delay: Long = 500L,
call: (data: T) -> Unit
) : CoroutineScope {
override val coroutineContext: CoroutineContext = Dispatchers.Main
private var debounce = delay // ms
private var job: Job? = null
init {
data.observeForever { data ->
job?.cancel()
job = launch {
delay(debounce)
call(data)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment