android - 协程没有启动?

标签 android higher-order-functions kotlin-coroutines coroutinescope androidx-lifecycle

基于此post throttleFirst 函数:

fun <T> throttleFirst(
    skipMs: Long = 700L,
    scope: CoroutineScope = viewModelScope,
    action: (T) -> Unit
): (T) -> Unit {
    var throttleJob: Job? = null
    return { param: T ->
        if (throttleJob?.isCompleted != false) {
            throttleJob = coroutineScope.launch {
                destinationFunction(param)
                delay(skipMs)
            }
        }
    }
}

我是这样使用它的:

查看

<Button
    android:onClick="@{viewModel.myClickListener}"
.../>

View 模型:

fun myClickListener() = View.OnClickListener { _ ->
    throttleClick(clickAction = {
        //do things
    })
}

基础 View 模型:

protected fun throttleClick(millis: Long = 700L, clickAction: (Unit) -> Unit): (Unit) -> Unit  {
    throttleFirst(millis, scope = viewModelScope, action = clickAction)
}

但没有任何反应,clickAction 未达到。调试时,当它点击 return { param: T -> 并且返回函数 (throttleJob?.isCompleted... 代码) 永远不会被调用时,逐步结束.
我做错了什么?

Patrick 的帮助下

编辑最终的解决方案是:

View 模型

private val myThrottleClick = throttleClick(clickAction = {
    //do things
})

fun myClickListener() = View.OnClickListener { myThrottleClick(Unit) }

基础 View 模型

protected fun throttleClick(millis: Long = 700L, clickAction: (Unit) -> Unit): (Unit) -> Unit {
    return throttleFirst(millis, action = clickAction)
}

最佳答案

您的 throttleFirst 函数生成点击监听器,因此您必须将其存储在点击监听器范围之外的 val 中。即

val clickListener = throttleFirst { doStuff() }

fun myClickListener() = View.OnClickListener { _ -> clickListener() }

您可以完全取消 myClickListener 函数,只在 xml 中引用 clickListener

关于android - 协程没有启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59413001/

相关文章:

ios - 查找具有匹配键的字典值的总和

Swift 4 - 用数组过滤数组

javascript - 高阶函数作为 Javascript 中对象的属性

android - 如何从协程范围返回值

android - 选项 -no-engine 导致 Android 的 OpenSSL 构建出现问题

具有所有资源的 Android 更新应用程序,无需询问 All vs New

android - 为什么 Android Datastore 总是通过运行阻塞返回相同的值

android - Kotlin 协程 java.lang.IllegalStateException : Task is not yet complete even though task returns a value

android - 有多少 ViewGroup(LinearLayout、Relative、Grid 等)被认为太多了?

android - WorkManager 的 ForceStopRunnable 中的 SQLiteException