Skip to content

Instantly share code, notes, and snippets.

@MohamedGouaouri
Last active May 13, 2023 12:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MohamedGouaouri/12c73977a24f57615976e933b9e4ab54 to your computer and use it in GitHub Desktop.
Save MohamedGouaouri/12c73977a24f57615976e933b9e4ab54 to your computer and use it in GitHub Desktop.
@Composable
fun <T> T.useDebounce(
delayMillis: Long = 300L,
// 1. couroutine scope
coroutineScope: CoroutineScope = rememberCoroutineScope(),
onChange: (T) -> Unit
): T{
// 2. updating state
val state by rememberUpdatedState(this)
// 3. launching the side-effect handler
DisposableEffect(state){
val job = coroutineScope.launch {
delay(delayMillis)
onChange(state)
}
onDispose {
job.cancel()
}
}
return state
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment