Koltin协程防抖点击

传统方式(Java和Kotlin)
private var lastClickTime: Long = 0
view?.setOnClickListener {
    if (System.currentTimeMillis() - lastClickTime <= 500L) {
        lastClickTime = System.currentTimeMillis()
        return@setOnClickListener
    }

    XXXXX
}
缺点:每次都要写重复代码


RxBinding方式(Java和Kotlin)
依赖RxBinding:
implementation 'com.jakewharton.rxbinding2:rxbinding:2.2.0'

使用:

RxView
    .clicks(view!!)
    .throttleFirst(500L, TimeUnit.MILLISECONDS)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe {
        XXXXX
    }
缺点:需要依赖三方库


Kotlin扩展函数+协程(Kotlin)
编写扩展函数:
fun View.setDebounceClickListener(listener: View.OnClickListener, time: Long = 500L) {
    var job: Job? = null
    this.setOnClickListener {
        job?.cancel()
        job = CoroutineScope(Dispatchers.Main).launch {
            delay(time)
            listener.onClick(it)
        }
    }
}
使用:
view?.setDebounceClickListener(
    {
        XXXXX
    }
)
缺点:只能Kotlin使用,不支持Java

你可能感兴趣的:(Koltin协程防抖点击)