Last active
December 19, 2021 10:17
-
-
Save yoonseopshin/b41cfc95b2e33c2d1717e54eb3620295 to your computer and use it in GitHub Desktop.
Android throttle click extension implementation (for single click)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OnThrottleClickListener( | |
private val dispatcher: CoroutineDispatcher, | |
private val onClickListener: View.OnClickListener, | |
private val interval: Long, | |
) : View.OnClickListener { | |
private var isClickable = true | |
override fun onClick(view: View) { | |
if (isClickable) { | |
isClickable = false | |
view.findViewTreeLifecycleOwner()?.let { lifecycleOwner -> | |
lifecycleOwner.lifecycle.coroutineScope.launch(dispatcher) { | |
onClickListener.onClick(view) | |
delay(interval) | |
isClickable = true | |
} | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun View.setOnThrottleClick( | |
dispatcher: CoroutineDispatcher = Dispatchers.Main, | |
interval: Long = 500L, | |
action: (view: View) -> Unit = {} | |
) { | |
val listener = View.OnClickListener { action(it) } | |
setOnClickListener(OnThrottleClickListener(dispatcher, listener, interval)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment