2

I've got a simple navhost that looks like this:

@Composable
fun NavigationComponent(
    navController: NavHostController,
    context: Context,
) {

    NavHost(
        navController = navController,
        startDestination = Screen.MainScreen.route
    ) {

        composable(Screen.MainScreen.route) {
            MainScreen(navController = navController)
        }


        composable(
            route = Screen.NewPlanScreen.route,
        ) {
            NewPlanScreen(context = context, navController = navController)
        }

    }
}

It is called from main activity like this:

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    @OptIn(ExperimentalAnimationApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val context = this

            val navController: NavHostController = rememberNavController()
            MainTheme(
                darkTheme = isDarkMode.value
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(AppTheme.colors.primaryBackground)
                ) {
                    NavigationComponent(navController = navController, context = context)
                }
            }
        }
    }
}

NewPlanScreen has a viewmodel that is provided by dagger hilt:

@Composable
fun NewPlanScreen(
    viewModel: NewPlanScreenViewModel = hiltViewModel(),
    navController: NavController,
    context: Context
) {
//...
}

Also, the NewPlanScreenViewModel has a @HiltViewModel annotation and an injected constructor.

And in the MainScreen I use

navController.navigate(Screen.NewPlanScreen.route)

but when I press a back button on a phone to navigate back to main screen and then call the

navController.navigate(Screen.NewPlanScreen.route)

again, a new ViewModel for a NewPlan is created. What am I doing wrong?

ruskaof
  • 107
  • 13
  • 1
    this is expected behaviour - as soon as navigation route is removed from the back stack, the view model is getting destroyed. If you need to save it, you have pro use `saveState` and `restoreState` parameter, check out navigation bar [example](https://developer.android.com/jetpack/compose/navigation#bottom-nav) in documentation – Phil Dukhov May 10 '22 at 14:40
  • @PylypDukhov thanks! but when I use the same code with popUpTo(navController.graph.findStartDestination().id) {save state = true}, restorestate = true on navigation to the NewPlanScreen, nothing changes because I cannot save the state when popping from the screen using a back button. – ruskaof May 10 '22 at 15:31
  • 1
    You can override buck button press https://stackoverflow.com/a/69151539/3585796 – Phil Dukhov May 10 '22 at 16:11
  • thanks a lot, i would mark your comment as a correct answer if i could – ruskaof May 10 '22 at 18:41

0 Answers0