CodexBloom - Programming Q&A Platform

Custom ViewModel not retaining state after configuration change in Android 14

👀 Views: 73 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
android viewmodel kotlin configuration-change jetpack Kotlin

I'm upgrading from an older version and I'm testing a new approach and I'm working with an scenario where my custom `ViewModel` is not retaining its state after a configuration change, specifically when rotating the device... I have set up my `ViewModel` to hold some user data and UI state. However, after the rotation, the `ViewModel` seems to be getting recreated instead of allowing me to retain the data. I'm using Kotlin and my `ViewModel` is defined as follows: ```kotlin class UserViewModel : ViewModel() { var userData: String? = null var isDataLoaded: Boolean = false } ``` In my `Activity`, I'm retrieving the `ViewModel` like this: ```kotlin class MainActivity : AppCompatActivity() { private lateinit var userViewModel: UserViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) userViewModel = ViewModelProvider(this).get(UserViewModel::class.java) if (userViewModel.isDataLoaded) { // populate UI with userData } else { loadData() // Function to load data } } } ``` I also have the `loadData` function that sets `userViewModel.userData` and marks `isDataLoaded` as `true`. The question I'm working with is that during the rotation, the `userViewModel` seems to be re-instantiated, and I lose the state. I have tried using `ViewModelProvider(this)` and `ViewModelProvider(this, viewModelFactory)` with a custom factory, but the scenario continues. I received the following unexpected log message during rotation: ``` I/ViewModel: ViewModel created for UserViewModel ``` This indicates that a new instance is being created instead of retaining the existing one. Any suggestions on how to properly retain the state of my `ViewModel` across configuration changes? I'm currently targeting Android 14 and using the latest Jetpack libraries. Thanks in advance! This is happening in both development and production on macOS. Thanks for your help in advance! I'm working with Kotlin in a Docker container on CentOS. How would you solve this?