Created
January 28, 2019 13:07
-
-
Save ywett02/c2183f9aab9ec89f9eeb1ed9e95cf3a4 to your computer and use it in GitHub Desktop.
Simple debounce extension for LiveData
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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