Skip to content

Instantly share code, notes, and snippets.

@thegarlynch
Created January 4, 2022 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thegarlynch/81efd33680b415c211e8c863b9e3077f to your computer and use it in GitHub Desktop.
Save thegarlynch/81efd33680b415c211e8c863b9e3077f to your computer and use it in GitHub Desktop.
Debounce Action Compose.. So click won't triggered twice
import android.os.SystemClock
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
/**
* Use this for debouncing action.
* This will returned a closure that will transformed the [action]
* so into debounced closure
*
* How to use :
*
* @Composable
* fun Example(onClick : () -> Unit){
*
* Button(
* text : "CLICK",
* onClick : debounceCompose(onClick)
* )
*
* }
*
*/
@Composable
fun debounceCompose(debounceTime: Long = 500L, action: () -> Unit): () -> Unit {
val debouncedAction = remember(action) {
var lastClickTime: Long = 0
{
if (SystemClock.elapsedRealtime() - lastClickTime >= debounceTime) {
lastClickTime = SystemClock.elapsedRealtime()
action()
}
}
}
return debouncedAction
}
@Composable
fun <T> debounceCompose(debounceTime: Long = 500L, action: (T) -> Unit): (T) -> Unit {
val debouncedAction = remember(action) {
var lastClickTime: Long = 0
val callback: (T) -> Unit = {
if (SystemClock.elapsedRealtime() - lastClickTime >= debounceTime) {
lastClickTime = SystemClock.elapsedRealtime()
action(it)
}
}
callback
}
return debouncedAction
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment