我是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()
}
}但它不起作用。你能帮我修正一下协程的表达式吗?
发布于 2020-02-21 21:49:39
所以,我找到了解决方案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时取消协程,因为它是自动工作的!但是对于处理程序,您必须调用removeCallbacksAndMessages onDestroy
https://stackoverflow.com/questions/60338482
复制相似问题