androidandroid-jetpack-composekotlin-flowjetpack-compose-navigation

Compose conditional navigation if user is already logged in


I have an app consisting of a Login screen and a Home screen.

Once the user logs in successfully I navigate to home screen, and use DataStore to save the successful login.

Once the app is closed of course the login screen is presented, as it's the startDestination in my NavHost, but I want to somehow check if the user has already logged in previously and if so navigate directly to the Home screen.

I've tried in the onCreate method retrieving the saved login state from DataStore, and changing the startDestination parameter based on that but, because it's a state, it requires a default value. By providing a default value for the isLoggedIn, the first emmited value will cause to show the login screen momentarily and then navigate to the home Screen.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val appViewModel by inject<AppViewModel>()

        //Default value to false 
        // (set to true happends the same, first home screen then navigates to login screen)
        var isLoggedIn: Boolean by mutableStateOf(false) 

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                appViewModel.isLoggedIn.collect {
                    isLoggedIn = it
                }
            }
        }

        /*Collect appViewModel.isLoggedIn, which is a flow<Boolean> of preference from DataStore, 
        containing a boolean indicating if the user has successfully logged in before*/
        setContent {
            PrimeTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.secondary
                ) { // Here I call the Navhost with different startDestination based on isLoggedIn parameter
                   RootView(isLoggedIn) 
                }
            }
        }
    }

I would like to achieve something similar to other apps, where you log in once, and then the app always starts in the "home" screen.

Is there any better way to do this?

Thanks


Solution

  • You can handle this in the Splash Screen. Check the user's state in the Splash Screen and then navigate based on that state. Set your Splash Screen as the startDestination or use it as a dependent activity, either approach is fine.