Junior — Middle
How to implement a delay mechanism for sending a search query until the user finishes input?
sobes.tech AI
Answer from AI
To implement a delay in sending a search request until the user finishes typing, a "debounce" mechanism is usually used — a delay that resets with each new input.
In Android, this can be done using Handler and Runnable:
private val handler = Handler(Looper.getMainLooper())
private var searchRunnable: Runnable? = null
fun onSearchTextChanged(query: String) {
searchRunnable?.let { handler.removeCallbacks(it) }
searchRunnable = Runnable {
performSearch(query) // function to send the request
}
handler.postDelayed(searchRunnable!!, 500) // delay of 500 ms
}
Each time the text changes, the previous scheduled request is canceled, and a new one is started with a delay. If the user continues typing, the request will not be sent until they stop typing for 500 ms.
This reduces the number of requests and improves performance.