Skip to content

Instantly share code, notes, and snippets.

@KwabenBerko
Created April 5, 2021 13:33
Show Gist options
  • Save KwabenBerko/7f87e0dbac8ae618731dfc83cec1fc44 to your computer and use it in GitHub Desktop.
Save KwabenBerko/7f87e0dbac8ae618731dfc83cec1fc44 to your computer and use it in GitHub Desktop.
Debounced SearchView
@ExperimentalCoroutinesApi
fun SearchView.doOnQueryTextChanged(): Flow<CharSequence?> {
return callbackFlow<CharSequence?> {
val listener = object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?) = false
override fun onQueryTextChange(newText: String?): Boolean {
offer(newText)
return false
}
}
setOnQueryTextListener(listener)
awaitClose { setOnQueryTextListener(null) }
}.onStart { emit(query) }
}
@KwabenBerko
Copy link
Author

Usage:

searchView.doOnQueryTextChanged()
            .distinctUntilChanged()
            .debounce(300L)
            .onEach { //Do search here }
            .launchIn(lifecycleScope)

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