I saw this example and I'm wondering is there any objective reason to implement this using Coroutines delay instead of Android Handler postDelayed?
In case the link dies the code from example is below:
val watcher = object :TextWatcher{
private var searchFor = ""
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val searchText = s.toString().trim()
if (searchText == searchFor)
return
searchFor = searchText
launch {
delay(300) //debounce timeOut
if (searchText != searchFor)
return@launch
// do our magic here
}
}
override fun afterTextChanged(s: Editable?) = Unit
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
}
EDIT: To clarify, the delay from Coroutines can be replaced with the delay from Android Handler postDelayed. The difference is that the Coroutines will perform the delay being suspended, while the Android Handler will perform the delay by storing a message into the message queue of the thread to be executed at a later point. Seemingly the effect is the same, the difference is in the how the delay is performed. Is there any objective reason why one or the other would be better here?
EDIT2: Turns out that under the hood Coroutine dispatchers will use something like an Android Handler. Refer to this for more detail. This implies that introducing coroutines for a simple delay isn't worth it.
Yes, there is an objective reason to prefer delay in some cases. If you need to carry variables from before the delay, or put it in a loop, using delay will give you much clearer code. However, in this particular case, it doesn't add much, because you are delaying after launching the coroutine right away, of course. But it won't have any downsides either, so you might prefer to do it if you think the code looks cleaner that way.
All the coroutines stuff is implemented in terms of standard framework stuff. Under the hood, it will always be Handler and other things you can use directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With