Fragment not retaining state with ViewModel when navigating back after configuration change on Android 14
I need help solving I'm experiencing an issue where my Fragment is not retaining its state when navigating back after a configuration change (like screen rotation) while using ViewModel... I'm using Android 14 and the Fragment lifecycle seems to be misbehaving. I have set up my ViewModel like this: ```kotlin class MyViewModel : ViewModel() { var counter = 0 fun increment() { counter++ } } ``` In my Fragment, I initialize the ViewModel like this: ```kotlin class MyFragment : Fragment() { private lateinit var viewModel: MyViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProvider(this).get(MyViewModel::class.java) // Other initialization code } } ``` When I increment the counter and then rotate the device, the Fragment is recreated, and I expected the counter to retain its value. However, it resets to zero, indicating that the ViewModel is not retaining state correctly. I've also tried using `savedInstanceState` to store the counter, but it's cumbersome and not the cleanest solution. Here's the code for that: ```kotlin override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("counter", viewModel.counter) } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) savedInstanceState?.let { viewModel.counter = it.getInt("counter") } } ``` This also feels redundant since the purpose of using ViewModel is to survive configuration changes. Is there a correct way to handle state retention for Fragments using ViewModels in this scenario? Any insights or guidance on best practices would be greatly appreciated! What am I doing wrong? For context: I'm using Kotlin on Linux. Any feedback is welcome!