Created
January 27, 2021 02:24
-
-
Save addeeandra/f143f224d8328c3c28ddab9f8cae6244 to your computer and use it in GitHub Desktop.
Debounce wrapper for LiveData observer
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
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