Skip to content

Instantly share code, notes, and snippets.

@iVamsi
Created September 14, 2025 03:53
Show Gist options
  • Save iVamsi/511321aa898f1c2a97cfe9b290494584 to your computer and use it in GitHub Desktop.
Save iVamsi/511321aa898f1c2a97cfe9b290494584 to your computer and use it in GitHub Desktop.
LaunchedEffect(currentMessage.value) {
currentMessage.value?.let { message ->
val result: SnackbarResult
if (message.duration is SnackbarDurationWrapper.Custom) {
// Create two competing operations
val snackbarDeferred = async {
snackbarHostState.showSnackbar(
message = message.text,
actionLabel = message.actionLabel,
duration = SnackbarDuration.Indefinite // Never auto-dismiss
)
}
val timeoutDeferred = async {
delay(message.duration.getMilliseconds())
SnackbarResult.Dismissed // Timer won
}
// Race them - winner takes all
result = select {
snackbarDeferred.onAwait { userResult ->
timeoutDeferred.cancel() // Cancel timer
userResult
}
timeoutDeferred.onAwait { timerResult ->
snackbarHostState.currentSnackbarData?.dismiss()
snackbarDeferred.cancel() // Cancel snackbar
timerResult
}
}
} else {
// Use standard Material3 behavior
result = snackbarHostState.showSnackbar(
message = message.text,
actionLabel = message.actionLabel,
duration = message.duration.getStandardDuration()
)
}
// Handle the result
when (result) {
SnackbarResult.ActionPerformed -> message.onAction?.invoke()
SnackbarResult.Dismissed -> { /* Handle dismissal */ }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment