Skip to content

Instantly share code, notes, and snippets.

@ywett02
Created January 28, 2019 13:07
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 ywett02/c2183f9aab9ec89f9eeb1ed9e95cf3a4 to your computer and use it in GitHub Desktop.
Save ywett02/c2183f9aab9ec89f9eeb1ed9e95cf3a4 to your computer and use it in GitHub Desktop.
Simple debounce extension for LiveData
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MediatorLiveData
import android.os.Handler
import android.os.Looper
fun <T> LiveData<T>.debounce(duration: Long = 1000L) = MediatorLiveData<T>().also { mld ->
val source = this
val handler = Handler(Looper.getMainLooper())
val runnable = Runnable {
mld.value = source.value
}
mld.addSource(source) {
handler.removeCallbacks(runnable)
handler.postDelayed(runnable, duration)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment