java - 尝试为`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 的表达好吗?
解决方案
所以,我在这里找到了解决方案。并且刚刚修改了一点:
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
推荐阅读
- c++ - 为什么在 x64 构建的 ARM 构建中缺少 CoCreateInstanceFromApp?
- java - 一个列表的多个 JComboboxes
- php - 在 Woocommerce 中更改交叉销售的订购参数
- java - 强制一个新的 HTTP 响应
- raku - 在 Perl 6 中是导出和绑定
- angular - .catch 在 Observable 类型上不存在
- python - 在列表理解中调用非纯函数
- symfony4 - 使用 Symfony4、codeception 和 AspectMock 模拟错误
- android - 返回时选项卡中的 WebView 空白
- vue.js - 动态更改 SPA 的 API 路由