androidkotlinandroid-jetpack-compose

Handling navigation start destination based on access token availability


I'm new to Android development, and currently I'm working on app building with Jetpack Compose. Note that I have already set up app navigation and store access token, which I get from the backend server on the data store. However, I'm still confused about the start destination for navigation. Basically, I need to set the start destination of the navigation based on the access token availability on the datastore. If the access token is available in the data store, I want to navigate to the home page or else login page. How to do this ? What would be a suitable solution for this ?

Thanks in advance


Solution

  • You didn't provide the code you have so far, so I will fill in the gaps; adapt as needed. I further assume you use the standard approach for something like this, with a view model providing the access token as a StateFlow. I assume the type is StateFlow<String?>, with the content being empty when no token is available and an initial value of null until the data store returns.

    Then your top-most composable could look something like this:

    @Composable
    fun App() {
        val viewModel: AppViewModel = viewModel()
    
        val accessToken by viewModel.accessToken.collectAsStateWithLifecycle()
        val startDestination = when (accessToken) {
            null -> null
            "" -> LoginRoute
            else -> HomeRoute
        }
    
        if (startDestination == null) CircularProgressIndicator()
        else NavHost(rememberNavController(), startDestination) {
            composable<LoginRoute> {
                LoginScreen()
            }
            composable<HomeRoute> {
                HomeScreen()
            }
        }
    }
    

    The key is that you differentiate the state where the data store hasn't yet provided a value (null) and wait with your navigation until it is available. I chose CircularProgressIndicator() as a placeholder here so the user has some feedback. You can replace it with whatever you like.

    Only when the data store eventually returns, the NavHost is displayed with the usual navigation logic. And here you can provide the start destination.