尝试为 `handler` 编写 `coroutine` 模拟,但不起作用

Try to write `coroutine` analog for `handler`, but not work

我是 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()
    }
}

但是不行。 你能修正我对协程的表达吗?

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

 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