Kotlin Android debounce

前端 未结 10 857
佛祖请我去吃肉
佛祖请我去吃肉 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:17

    I have created a single extension function from the old answers of stack overflow:

    fun View.clickWithDebounce(debounceTime: Long = 600L, action: () -> Unit) {
        this.setOnClickListener(object : View.OnClickListener {
            private var lastClickTime: Long = 0
    
            override fun onClick(v: View) {
                if (SystemClock.elapsedRealtime() - lastClickTime < debounceTime) return
                else action()
    
                lastClickTime = SystemClock.elapsedRealtime()
            }
        })
    }
    

    View onClick using below code:

    buttonShare.clickWithDebounce { 
       // Do anything you want
    }
    

提交回复
热议问题