Last active
November 11, 2023 13:56
-
-
Save deveshmittal/30842b7e05a17329c96238977d4a168e to your computer and use it in GitHub Desktop.
Debounce using coroutines on a view
This file contains hidden or 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
| object ViewExt{ | |
| fun View.setDebounceClickListener( | |
| duration: Duration = 300.milliseconds, | |
| action: (View) -> Unit | |
| ) { | |
| this.setDebounceClickListener(duration.inWholeMilliseconds, action) | |
| } | |
| private fun View.setDebounceClickListener( | |
| timeInMillis: Long, | |
| action: (View) -> Unit | |
| ) { | |
| var debounceJob = AtomicReference<Job?>(null) | |
| val viewScope = findViewTreeLifecycleOwner()?.lifecycleScope ?: CoroutineScope(Dispatchers.Main + SupervisorJob()) | |
| setOnClickListener{ view -> | |
| debounceJob.get()?.cancel() | |
| debounceJob.set(viewScope.launch { | |
| delay(timeInMillis) | |
| action(view) | |
| }) | |
| } | |
| addOnAttachStateChangeListener(object:View.OnAttachStateChangeListener{ | |
| override fun onViewAttachedToWindow(p0: View) { | |
| } | |
| override fun onViewDetachedFromWindow(p0: View) { | |
| debounceJob.get()?.cancel() | |
| } | |
| }) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment