-
-
Save snyderra/6d62405ad407e641e4b80e0e160facef to your computer and use it in GitHub Desktop.
Simple debounce extension for LiveData by using Coroutines
This file contains hidden or 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 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 | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment