Throttle onQueryTextChange in SearchView
If you are using Kotlin and coroutines you could do the following:
var queryTextChangedJob: Job? = null
...
fun onQueryTextChange(query: String) {
queryTextChangedJob?.cancel()
queryTextChangedJob = launch(Dispatchers.Main) {
delay(500)
performSearch(query)
}
}
Building on aherrick's code, I have a better solution. Instead of using a boolean 'canRun', declare a runnable variable and clear the callback queue on the handler each time the query text is changed. This is the code I ended up using:
@Override
public boolean onQueryTextChange(final String newText) {
searchText = newText;
// Remove all previous callbacks.
handler.removeCallbacks(runnable);
runnable = new Runnable() {
@Override
public void run() {
// Your code here.
}
};
handler.postDelayed(runnable, 500);
return false;
}