协程不开始吗? [英] Coroutine doens't start?

查看:131
本文介绍了协程不开始吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此帖子 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}"
.../>

ViewModel:

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

BaseViewModel :

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

但没有任何反应,未达到 clickAction .在调试过程中,分步操作在到达return { param: T ->时结束,并且永不调用返回函数(throttleJob?.isCompleted ...代码).
我在做什么错了?

But nothing happens, the clickAction is not reached. While debugging, step-by-step ends when it hits return { param: T -> and that returning function (throttleJob?.isCompleted... code) is never called.
What am I doing wrong?

编辑,在最终解决方案 Patrick 的帮助下是:

EDIT with the help from Patrick the final solution is:

ViewModel

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

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

BaseViewModel

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

推荐答案

您的throttleFirst函数创建一个点击监听器,因此您必须将其存储在点击监听器范围之外的val中.即

Your throttleFirst function makes a click listener, so you must store it in a val outside of your click listeners scope. i.e.

val clickListener = throttleFirst { doStuff() }

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

您也许可以完全取消使用myClickListener函数,而只需在xml中引用clickListener.

You may be able to do away with the myClickListener function entirely and just reference clickListener in xml.

这篇关于协程不开始吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆