Kotlin Android debounce

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

    A more simple and generic solution is to use a function that returns a function that does the debounce logic, and store that in a val.

    fun  debounce(delayMs: Long = 500L,
                       coroutineContext: CoroutineContext,
                       f: (T) -> Unit): (T) -> Unit {
        var debounceJob: Job? = null
        return { param: T ->
            if (debounceJob?.isCompleted != false) {
                debounceJob = CoroutineScope(coroutineContext).launch {
                    delay(delayMs)
                    f(param)
                }
            }
        }
    }
    

    Now it can be used with:

    val handleClickEventsDebounced = debounce(500, coroutineContext) {
        doStuff()
    }
    
    fun initViews() {
       myButton.setOnClickListener { handleClickEventsDebounced(Unit) }
    }
    

提交回复
热议问题