androidnavigationandroid-jetpack-composevoyager

Using the voyager navigation to handle back pressed after login screen, should pop the login screen


I am using the voyager library for navigation in my android app.

https://voyager.adriel.cafe/navigation/ version 1.0.0

But I have an issue with navigation from the login screen to the home screen.

login screen ==> home screen

However, once the user has logged in the LoginScreen should be popped so the user can't navigate back to it. But when using the system backpressed it will try and open the login screen again.

This is my LoginScreeRoute

object LoginScreenRoot : Screen {

    @Composable
    override fun Content() {
        val loginViewModel = koinViewModel<LoginViewModel>()
        val navigator = LocalNavigator.currentOrThrow

        LoginScreen(
            loginState = loginViewModel.loginState,
            onLoginAction = loginViewModel::loginAction,
            onLoginSuccess = {
                /** Navigate to the home screen */
                Timber.d("onLoginSuccess")
                navigator.popAll()  // Try and pop the LoginScreen so we do go back to it
                navigator.push(HomeScreenRoute)
            },
            onLoginFailure = {
                /** Display message */
                Timber.d("onLoginFailure")
            },
            onForgotPassword = {
                /** Navigate to the home screen */
                Timber.d("onForgotPassword")
                navigator.push(ResetScreenRoute)
            }
        )
    }
}

And this is my HomeScreen

object HomeScreenRoute : Screen {

    @Composable
    override fun Content() {
        val homeViewModel = koinViewModel<HomeViewModel>()
        val homeState = homeViewModel.homeState
        val navigator = LocalNavigator.currentOrThrow

        HomeScreen(
            onForwardButtonClicked = {
                navigator.push(SurveyStartScreenRoute)
            },
            homeState = homeState
        )
    }
}

And in my MainActivity

setContent {
            BusbySurveyTheme {
                val scope = rememberCoroutineScope()

                if(mainViewModel.mainState.isLoggedIn) {
                    Navigator(screen = HomeScreenRoute)
                }
                else {
                    GradientBackground {
                        Navigator(screen = LoginScreenRoot)
                    }
                }
            }
        }

Solution

  • Replace

    navigator.popAll()
    navigator.push(HomeScreenRoute)
    

    With

    navigator.replace(HomeScreenRoute)