【问题标题】:Try to write `coroutine` analog for `handler`, but not work尝试为`handler`编写`coroutine`模拟,但不起作用
【发布时间】:2020-02-21 12:15:41
【问题描述】:

我是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 的表达方式吗?

【问题讨论】:

  • 你不能只是取消协程作用域然后希望继续使用它。您可以通过取消特定作业来修复它,但它仍然是不雅的代码。

标签: java android kotlin handler kotlin-coroutines


【解决方案1】:

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

 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时不需要取消协程,因为它会自动运行! 但是对于handler,你必须调用removeCallbacksAndMessagesonDestroy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    相关资源
    最近更新 更多