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.