Android postDelay与协同程序延迟

时间:2019-09-24 09:08:46

标签: android kotlin android-handler kotlin-coroutines

我看到了this的示例,我想知道是否有任何客观原因使用协程delay而不是Android处理程序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
}

编辑:为明确起见,可以将Coroutines中的delay替换为Android处理程序postDelayed中的延迟。区别在于协程将执行延迟被暂停,而Android处理程序将通过将消息存储到线程的消息队列中以在稍后执行该延迟来执行延迟。看起来效果是相同的,不同之处在于执行延迟的方式。有任何客观原因可以使这里的一个或另一个变得更好吗?

EDIT2:事实证明,Coroutine调度程序将在内部使用类似Android Handler的东西。有关更多详细信息,请参见this。这意味着引入协程简单延迟是不值得的。

1 个答案:

答案 0 :(得分:3)

基本上,协程要比处理程序线程好得多,每当您使用处理程序时,它都会在执行post delay方法后在主ui线程中运行可运行对象,但是归因于协程,您始终可以在不同的上下文中指定延迟,例如启动时{ }用于在ui线程中执行协程,或者如果您需要后台延迟,则可以使用aync {}。

此外,处理程序仅限于将所需的代码执行到一个可运行的程序中,而在延迟之后,如果要从断点恢复操作,将很难做到这一点。

因此,协程从根本上简化了我们的流程,如果您要调用延迟,它将在特定时间暂停或取消您的方法,然后将其从延迟发生的位置恢复。

更具体地看一下例如:-

suspend fun myfunc(){
print("Hello") //prints a hello
delay(300) //this line suspends your function for 300 milliseconds
print("World") //when delay is over world will be printed  
}