Kotlin Android debounce

前端 未结 10 828
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 11:07

Is there any fancy way to implement debounce logic with Kotlin Android?

I\'m not using Rx in project.

There is a way in Java, but it is too big

10条回答
  •  遥遥无期
    2020-12-05 11:34

    Using tags seems to be a more reliable way especially when working with RecyclerView.ViewHolder views.

    e.g.

    fun View.debounceClick(debounceTime: Long = 1000L, action: () -> Unit) {
        setOnClickListener {
            when {
                tag != null && (tag as Long) > System.currentTimeMillis() -> return@setOnClickListener
                else -> {
                    tag = System.currentTimeMillis() + debounceTime
                    action()
                }
            }
        }
    }
    

    Usage:

    debounceClick {
        // code block...
    }
    

提交回复
热议问题