Kotlin Android debounce

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

    @masterwork's answer worked perfectly fine. Here it is for ImageButton with compiler warnings removed:

    @ExperimentalCoroutinesApi // This is still experimental API
    fun ImageButton.onClicked() = callbackFlow {
        setOnClickListener { offer(Unit) }
        awaitClose { setOnClickListener(null) }
    }
    
    // Listener for button
    val someButton = someView.findViewById(R.id.some_button)
    someButton
        .onClicked()
        .debounce(500) // 500ms debounce time
        .onEach {
            clickAction()
        }
        .launchIn(lifecycleScope)
    

提交回复
热议问题