我是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()
}
}
但这行不通。
您能为协程修复我的表情吗?
最佳答案
因此,我找到了解决方案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
关于java - 尝试为 `coroutine`编写 `handler`模拟,但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338482/