Trouble with State Management in Jetpack Compose while Navigating Between Screens with ViewModels
I'm migrating some code and I'm stuck on something that should probably be simple... I'm working with issues with maintaining the state of my ViewModel when navigating between different screens in my Jetpack Compose application. I'm using the Navigation component along with Hilt for dependency injection. While navigating from Screen A to Screen B, I expected the state in ViewModel A to continue, but it seems to be getting reset. Here's a simplified version of my setup: ```kotlin @HiltViewModel class ScreenAViewModel @Inject constructor() : ViewModel() { var count by mutableStateOf(0) fun increment() { count++ } } @Composable fun ScreenA(viewModel: ScreenAViewModel) { Column { Text(text = "Count: ${viewModel.count}") Button(onClick = { viewModel.increment() }) { Text("Increment") } Button(onClick = { navController.navigate("screen_b") }) { Text("Go to Screen B") } } } @Composable fun ScreenB() { // Screen B implementation } ``` The scenario arises when I navigate back to Screen A after visiting Screen B; the `count` resets to `0`. I've tried using `rememberSavedInstanceState()` in combination with `remember { mutableStateOf(...) }`, but that doesn't seem to retain the count when navigating back. My NavHost is set up correctly, and I'm using `viewModel()` to obtain the ViewModel in Screen A. What am I missing here? Is there a recommended approach for maintaining ViewModel state across navigation in Jetpack Compose? Any insights would be greatly appreciated! For context: I'm using Kotlin on macOS. Any ideas what could be causing this? For context: I'm using Kotlin on Linux. Am I missing something obvious? This is my first time working with Kotlin LTS. Any advice would be much appreciated. I'm coming from a different tech stack and learning Kotlin. How would you solve this?