Android postDelayed 与协程延迟

问题描述 投票:0回答:1

我看到了 this 示例,我想知道是否有客观原因使用协程

delay
而不是 Android Handler
postDelayed
来实现此功能?

如果链接失效,示例代码如下:

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
}

编辑:澄清一下,协程中的

delay
可以替换为 Android 处理程序
postDelayed
中的延迟。不同之处在于,Coroutines 会执行挂起的延迟,而 Android Handler 会通过将消息存储到稍后要执行的线程的消息队列中来执行延迟。看起来效果是一样的,区别在于延迟的执行方式。是否有任何客观原因说明其中一个或另一个会更好?

EDIT2:事实证明,协程调度程序在幕后将使用类似 Android 处理程序的东西。请参阅this了解更多详情。这意味着为了简单的延迟而引入协程是不值得的。

android kotlin android-handler kotlin-coroutines
1个回答
2
投票

是的,在某些情况下有客观原因选择

delay
。如果您需要在延迟之前携带变量,或者将其放入循环中,那么使用延迟将为您提供更清晰的代码。然而,在这种特殊情况下,它并没有增加太多,因为当然,你在立即启动协程后会延迟。但它也不会有任何缺点,所以如果您认为这样代码看起来更干净,您可能更愿意这样做。

所有协程内容都是根据标准框架内容实现的。在幕后,它始终是 Handler 和其他您可以直接使用的东西。

© www.soinside.com 2019 - 2024. All rights reserved.