I'm facing an issue with Android Jetpack Compose Snackbar in my application. I have a LazyColumn where each row is a SwipeToDismiss composable. On each swipe, I remove the row and show a Snackbar. However, if I swipe rows very frequently, a queue of Snackbars is created, and they appear one by one. I want to modify this behavior so that only the latest Snackbar is shown, and it immediately closes the previous one.
val scaffoldState = rememberScaffoldState()
LaunchedEffect(key1 = true) {
viewModel.uiEvent.collect { event ->
when (event) {
is UiEvent.ShowSnackBar -> {
val snackbarResult = scaffoldState.snackbarHostState.showSnackbar(
message = event.message,
actionLabel = event.action
)
when (snackbarResult) {
SnackbarResult.Dismissed -> {}
SnackbarResult.ActionPerformed -> viewModel.onEvent(MessageListEvent.OnUndoDeleteClick)
}
}
else -> Unit
}
}
}
You could try something like:
This way, when
uiEvent.valuechanges,LaunchedEffectwill cancel the previous coroutine and its snackbar will be automatically dismissed.