Skip to content

Instantly share code, notes, and snippets.

@mirmilad
Last active June 21, 2023 22:46
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mirmilad/f7feb8007d6b572150cb84fef0b65879 to your computer and use it in GitHub Desktop.
Save mirmilad/f7feb8007d6b572150cb84fef0b65879 to your computer and use it in GitHub Desktop.
Simple debounce extension for LiveData by using Coroutines
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
fun <T> LiveData<T>.debounce(duration: Long = 1000L, coroutineScope: CoroutineScope) = MediatorLiveData<T>().also { mld ->
val source = this
var job: Job? = null
mld.addSource(source) {
job?.cancel()
job = coroutineScope.launch {
delay(duration)
mld.value = source.value
}
}
}
@vaibhavpandeyvpz
Copy link

vaibhavpandeyvpz commented Aug 25, 2020

For folks wondering on how to use this:

model.q.debounce(500L, CoroutineScope(Dispatchers.Main))
    .observe(viewLifecycleOwner) { model.filter(it) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment