My question is related to the Compose navigation and screen rotation. After screen rotation, for some reason, as I understand, the composable is re-created and latest value of NavigationViewModel is taken and additional composable/screen is added into the backstack. What should be done to prevent adding new composable into backstack, after rotation?
@Composable
fun NavRoot() {
val navController = rememberNavController()
val viewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
}
navigationViewModel = hiltViewModel<NavigationViewmodel>(viewModelStoreOwner = viewModelStoreOwner)
NavigationHost(
navController = navController,
keys = navigationViewModel.keys,
navigationViewModel = navigationViewModel
)
}
@Composable
internal fun NavigationHost(
navController: NavHostController,
keys: List<NavigationKey>,
navigationViewModel: NavigationViewmodel,
) {
if (keys.isEmpty()) return
val startDestination = keys.first().key
val screenState by navigationViewModel.state.collectAsState(...)
when (val currentScreenState = screenState) {
...
navController.navigate(screenState.key)
}
NavHost(navController = navController, startDestination = startDestination) {
keys.forEach { screen ->
composable(screen.key) {
NavigationRouter(
screen = screen,
)
}
}
}
}
I tried to play with the remember nav controller and it did not help unfortunately :(