Hello guys! I have a question about conditional na...
# compose
s
Hello guys! I have a question about conditional navigation. User can see start destination screen (Dashboard) and transition to sign in screen when isn't logged. Chain: 1. Check boolean from datastore flow in start destination screen (Dashboard) 2. In the Dashboard screen: if(isLogged) { Dashboard composable } else navigate to sign in How to fix this issue?
s
Maybe I need check isLogged in the MainActivity and pass result down to composable with navController?
f
What exactly is your issue?
s
Red background is the start destination and from this start I'm immediately navigate to the screen with green box
f
Because you are not logged in?
s
Yes
User can see red only when logged
f
So everything works fine?
Or is the user currently logged in?
s
In the video user isn't logged and must see only green
f
That's due to how data store works. It does some IO and only then the value is available.
s
But I tested without datastore and this happens again. Even when I call navigate method in the launched effect
@Felix Schütz You can test it in dummy app
Copy code
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(color = MaterialTheme.colors.background) {
                    TestNavigation()
                }
            }
        }
    }
}


@Composable
fun TestNavigation() {
    val navController = rememberNavController()

    Box(modifier = Modifier.fillMaxSize()) {
        NavHost(navController = navController, startDestination = "dashboard") {
            composable("dashboard") {
                DashboardScreen(navController)
            }
            composable("login") {
                LoginScreen()
            }
        }
    }
}

@Composable
fun LoginScreen() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Red)
    )
}

@Composable
fun DashboardScreen(navController: NavController) {
    LaunchedEffect(Unit) {
        navController.navigate("login")
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Green)
    )
}
f
Independent of the problem, I would suggest you to use
popUpTo
. Otherwise, the back button will be unusable (navigate back to dashboard, which immediately navigates to login again).
Copy code
navController.navigate("login") {
    popUpTo(id = 0)
}
And regarding your problem: Unfortunately, I don't have a solution for that 😞 But at least the delay is shorter without data store (I think). Maybe it helps to preload the value in your view model while the app launches. Or show a loading indicator in the dashboard, an then remove the loading indicator if the user is logged in.