Issues with ViewModel Lifecycle and State Restoration in Android 12+ when Using SavedStateHandle
I'm encountering a problem with state restoration in my Android app that's targeting API level 31 (Android 12). I'm using a ViewModel along with `SavedStateHandle` to manage UI state, but it seems that after the configuration changes, some of the data is not being restored properly, leading to unexpected behaviors in my fragments. I have the following setup in my ViewModel where I'm trying to save and restore a simple counter value: ```kotlin class MyViewModel(private val state: SavedStateHandle) : ViewModel() { var counter: Int get() = state.get<Int>("counter") ?: 0 set(value) { state.set("counter", value) } fun incrementCounter() { counter++ } } ``` In my Fragment, I'm observing the counter 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) return inflater.inflate(R.layout.fragment_my, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.counter.observe(viewLifecycleOwner) { value -> // Update UI with counter value counterTextView.text = value.toString() } incrementButton.setOnClickListener { viewModel.incrementCounter() } } } ``` When I run the app, after rotating the device, the counter value resets to 0 instead of retaining its value. I added logs to check the saved state, and it seems that the `SavedStateHandle` does not hold the value after the rotation. I also tried using `setSavedState()` in `onSaveInstanceState()`, but that didn't help either. I've checked the documentation for `SavedStateHandle` and ensured that I'm following best practices, but I must be missing something. Any insights on how to properly retain the state across configuration changes in this setup would be greatly appreciated.