Problems with Jetpack Compose Navigation and ViewModel State Restoration on Configuration Change
I've tried everything I can think of but I've spent hours debugging this and I'm experiencing an scenario where my ViewModel state is not being restored correctly after a configuration change while using Jetpack Compose Navigation... I'm targeting Android 14 and using the latest versions of Jetpack Compose. I have a setup where I navigate from one screen to another, and I rely on the ViewModel to hold some state data. However, after a rotation, the ViewModel's data becomes null, resulting in unexpected behavior and crashes. Here's a simplified version of my code: ```kotlin @Composable fun FirstScreen(navController: NavHostController, viewModel: MyViewModel = viewModel()) { val state by viewModel.state.collectAsState() Column { Text(text = state.message) Button(onClick = { navController.navigate("second") }) { Text("Go to Second Screen") } } } @Composable fun SecondScreen(viewModel: MyViewModel = viewModel()) { // Some code to modify viewModel state } // In your NavHost setup NavHost(navController, startDestination = "first") { composable("first") { FirstScreen(navController) } composable("second") { SecondScreen() } } ``` In my ViewModel, I have a simple state defined as: ```kotlin class MyViewModel : ViewModel() { private val _state = mutableStateOf(MyState()) val state: State<MyState> = _state init { // Initialize state here } } ``` After rotating the device, I expect the `state.message` to retain its value, but it often resets to the initial value or null. I have tried adding `@ViewModelScoped` annotations and ensuring I'm not recreating the ViewModel unnecessarily, but the scenario continues. Is there a specific way to handle state restoration in Jetpack Compose with navigation, or any best practices I might be overlooking? Any insights would be greatly appreciated! I'm coming from a different tech stack and learning Kotlin. This is my first time working with Kotlin stable.