ViewModel Not Retaining State After Configuration Change in Android 13 with Hilt Dependency Injection
I'm wondering if anyone has experience with I tried several approaches but none seem to work... I'm working with an scenario where my ViewModel is not retaining its state after a configuration change, specifically when my activity is recreated in Android 13. I'm using Hilt for dependency injection and I've implemented a ViewModel that holds a MutableLiveData object to store the UI state. After the configuration change, the ViewModel seems to be getting recreated, and I lose the current state of the MutableLiveData. Hereβs what I have set up in my ViewModel: ```kotlin @HiltViewModel class MyViewModel @Inject constructor() : ViewModel() { private val _state = MutableLiveData<MyState>() val state: LiveData<MyState> get() = _state fun updateState(newState: MyState) { _state.value = newState } } ``` In my Activity, I'm observing the LiveData: ```kotlin class MyActivity : AppCompatActivity() { private val viewModel: MyViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_my) viewModel.state.observe(this) { state -> // Update UI based on state } } } ``` I also made sure to use the `by viewModels()` delegate to obtain my ViewModel instance. However, when I rotate the device, the value of `state` is reset to null, and I get the following warning in the logs: ``` E/ViewModelStore: want to find ViewModel for fragment ``` I've double-checked that I'm not creating a new instance of the ViewModel manually and that Hilt is set up properly in my project. I'm also using `Android Gradle Plugin 7.1.0`. Any insights on why the ViewModel is not retaining its state after the configuration change? Is there something I'm missing in the Hilt setup or ViewModel lifecycle management? Is there a better approach? For context: I'm using Kotlin on Windows 11. Could this be a known issue?