首页 > 解决方案 > 尝试为`handler`编写`coroutine`模拟,但不起作用

问题描述

我是新来的coroutines。所以现在我看看如何使用协程而不是处理程序

处理程序代码:

fun Handler.repostDelayed(func: Runnable, delay: Long) {
removeCallbacksAndMessages(null)
postDelayed(func, delay)
}

协程中的模拟

inline fun AppCompatActivity.repostDelayed(crossinline func: () -> Unit, delay: Long) {
    lifecycleScope.cancel()
    lifecycleScope.launch {
        delay(delay)  //debounce timeOut
        func()
    }
}

但它不起作用。请你修复我对 Coroutines 的表达好吗?

标签: javaandroidkotlinhandlerkotlin-coroutines

解决方案


所以,我在这里找到了解决方案。并且刚刚修改了一点:

 fun <T, V> CoroutineScope.debounce(
    waitMs: Long = 300L,
    destinationFunction: T.(V) -> Unit
): T.(V) -> Unit {
    var debounceJob: Job? = null
    return { param: V ->
        debounceJob?.cancel()
        debounceJob = launch {
            delay(waitMs)
            destinationFunction(param)
        }
    }
}

用法:

 private val delayFun: String.(Boolean) -> Unit = lifecycleScope.debounce(START_DELAY) {
        if(it){
            print(this)
        }
    }

     //call function
     "Hello world!".delayFun(true)

使用协程的好处是你不需要在查看时取消协程,onDesstroy因为它会自动运行!但是对于处理程序,您必须调用removeCallbacksAndMessages onDestroy


推荐阅读