Created
January 4, 2022 07:54
-
-
Save thegarlynch/81efd33680b415c211e8c863b9e3077f to your computer and use it in GitHub Desktop.
Debounce Action Compose.. So click won't triggered twice
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
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