CodexBloom - Programming Q&A Platform

Issue with ViewModel and LiveData not retaining state after configuration changes in Android 14 with Hilt

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-07
android kotlin hilt viewmodel livedata

I've looked through the documentation and I'm still confused about I'm facing an issue where my `ViewModel` and `LiveData` are not retaining their state after a configuration change on Android 14 devices... I've implemented Hilt for dependency injection, and I'm using `ViewModel` to manage UI-related data in a lifecycle-conscious way. However, after a screen rotation, my LiveData values seem to reset to their initial state. Here's a brief overview of my setup: ```kotlin @HiltViewModel class MyViewModel @Inject constructor(private val repository: MyRepository) : ViewModel() { private val _data = MutableLiveData<List<MyData>>() val data: LiveData<List<MyData>> = _data fun fetchData() { viewModelScope.launch { _data.value = repository.getData() } } } ``` In my fragment, I'm observing this LiveData: ```kotlin @AndroidEntryPoint class MyFragment : Fragment() { private val viewModel: MyViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.data.observe(viewLifecycleOwner) { data -> // Update UI with new data } viewModel.fetchData() } } ``` Initially, everything works fine, and the data is displayed correctly. However, after rotating the device, the data disappears, and the view model seems to re-fetch the data, which is not the intended behavior. I’ve checked that the ViewModel is scoped correctly to the Fragment, and I’m using `viewLifecycleOwner` for observing LiveData. I've tried adding `savedInstanceState` management, but that hasn't resolved the issue. Additionally, I have ensured that any repository calls are not being repeated unnecessarily during configuration changes. Is there something I might be missing in the way I set up my ViewModel with Hilt or in how I manage the lifecycle of my LiveData? Could it be related to scope or instantiation issues specific to Hilt on Android 14? For context: I'm using Kotlin on Ubuntu 20.04. Could someone point me to the right documentation?