Jetpack Compose Show Snackbar

November 2, 2021

Assuming I try to load data from firestore, and I would show error via snackbar.

@Composable
fun JourneyApp(viewModel: MainViewModel = viewModel()) {
    // snackbar setup
    // allow sequential snackbar message without overwriting each other
    val snackbarChannel = remember { Channel<String>(Channel.BUFFERED) } 
    val scaffoldState = rememberScaffoldState()

    snackbarChannel.trySend("Loading Data ....")

    val postsResource by viewModel.fetchPosts().collectAsState(initial = Resource.loading(null))
    val posts = postsResource.data ?: emptyList()


    if (postsResource.status == Status.ERROR) {
        snackbarChannel.trySend(postsResource.message ?: "Error")
    }

    LaunchedEffect(snackbarChannel) {
        snackbarChannel.receiveAsFlow().collect { message ->
            scaffoldState.snackbarHostState.showSnackbar(
                message = message
            )
            /*
            when (result) {
                SnackbarResult.ActionPerformed -> {
                    /* action has been performed */
                }
                SnackbarResult.Dismissed -> {
                    /* dismissed, no action needed */
                }
            }
             */
        }
    }


    Scaffold(
        scaffoldState = scaffoldState,
    ) { innerPadding ->

        LazyColumn(modifier = Modifier.padding(innerPadding)) {
            items(posts) { post ->
                Text(post.title)
            }
        }
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.