Android postDelayed vs Coroutines delay
Asked Answered
H

1

15

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.

Hanoverian answered 24/9, 2019 at 9:8 Comment(0)
K
2

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.

Kith answered 14/2, 2022 at 21:58 Comment(4)
Coroutines are framework-agnostic. They are a standard library of Kotlin, not Android...Oria
I was referring to how they are implemented in Android. In particular Dispatchers.Main, which has a special Android specific implementation based on Handler and Android specific stuff.Kith
Look at source code of Dispatchers.Main - it is part of kotlinx.coroutines package. There is no Android-specific implementation.Oria
No, Android specific code is an added module. Check out here: github.com/Kotlin/kotlinx.coroutines/tree/master/ui/…Kith

© 2022 - 2025 — McMap. All rights reserved.