Skip to content

Instantly share code, notes, and snippets.

@KwabenBerko
Created April 5, 2021 13:16
Show Gist options
  • Save KwabenBerko/f9a1506018fd9a030869ceedf081689e to your computer and use it in GitHub Desktop.
Save KwabenBerko/f9a1506018fd9a030869ceedf081689e to your computer and use it in GitHub Desktop.
Debounced Text Watcher
@ExperimentalCoroutinesApi
fun EditText.doAfterTextChanged(): Flow<CharSequence?> {
return callbackFlow<CharSequence?> {
val listener = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) =
Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable?) {
offer(s)
}
}
addTextChangedListener(listener)
awaitClose { removeTextChangedListener(listener) }
}.onStart { emit(text) }
}
@KwabenBerko
Copy link
Author

KwabenBerko commented Apr 5, 2021

Usage:

searchEditText.doAfterTextChanged()
                .distinctUntilChanged()
                .debounce(300)
                .onEach { //Do search Here }
                .launchIn(lifecycleScope)

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