Navigation with compose official doc have stated "...
# compose
r
Navigation with compose official doc have stated "You should only call navigate() as part of a callback and not as part of your composable itself, to avoid calling navigate() on every recomposition" so should I not do this? Check the thread for details.
Inside a composable function
Copy code
if (viewModel.isLoggedIn) {
    navController.navigate(Screens.Home.id){
        popUpTo(Screens.Authenticate.id){ inclusive = true }
    }
}
here isLoggedIn is a mutable state.
Copy code
var isLoggedIn by mutableStateOf(false)
    private set
t
No you shouldn’t do this. When adding animation the if block will be executed every frame
You should move the navigation call to a LaunchedEffect
Copy code
LaunchedEffect(viewModel.isLoggedIn) {
    if (viewModel.isLoggedIn) {
        navController.navigate(Screens.Home.id){
           popUpTo(Screens.Authenticate.id)
        }
    }

}
r
Ok. Thanks Another doubt. I want show a snackbar everytime a network error response comes from the network call. Should it be like this.
Copy code
if (viewModel.isNetworkError) {
    LaunchedEffect(key1 = viewModel.isNetworkError) {
        state.snackbarHostState.showSnackbar("Something went wrong!")
    }
}
or this
Copy code
if (viewModel.isNetworkError) {
    LaunchedEffect(key1 = state.snackbarHostState) {
        state.snackbarHostState.showSnackbar("Something went wrong!")
    }
}
t
It should be like this
Copy code
LaunchedEffect(key1 =          viewModel.isNetworkError) {
        if (viewModel.isNetworkError) {
   state.snackbarHostState.showSnackbar("Something went wrong!")
    }
}
When the key for launch effect change the code block will be executed.
r
But I found this piece of code in the compose sample JetNews app. @Tin Tran
Copy code
if (posts.hasError) {
    val errorMessage = stringResource(id = R.string.load_error)
    val retryMessage = stringResource(id = R.string.retry)

    // If onRefreshPosts or onErrorDismiss change while the LaunchedEffect is running,
    // don't restart the effect and use the latest lambda values.
    val onRefreshPostsState by rememberUpdatedState(onRefreshPosts)
    val onErrorDismissState by rememberUpdatedState(onErrorDismiss)

    // Show snackbar using a coroutine, when the coroutine is cancelled the snackbar will
    // automatically dismiss. This coroutine will cancel whenever posts.hasError is false
    // (thanks to the surrounding if statement) or if scaffoldState.snackbarHostState changes.
    LaunchedEffect(scaffoldState.snackbarHostState) {
        val snackbarResult = scaffoldState.snackbarHostState.showSnackbar(
            message = errorMessage,
            actionLabel = retryMessage
        )
        when (snackbarResult) {
            SnackbarResult.ActionPerformed -> onRefreshPostsState()
            SnackbarResult.Dismissed -> onErrorDismissState()
        }
    }
}
t
Oh I forgot you are using snackbar. In that case you can use it like the sample