CodexBloom - Programming Q&A Platform

Fragment ViewModel Sharing Not Persisting Across Configuration Changes in Android 14

👀 Views: 382 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-27
android viewmodel jetpack Kotlin

After trying multiple solutions online, I still can't figure this out. I'm prototyping a solution and I'm relatively new to this, so bear with me. I'm facing an issue where a shared ViewModel across two fragments is not retaining its state after a configuration change (like screen rotation). I'm using Android 14 and the latest version of the Jetpack libraries. I set up my fragments to share a ViewModel like this: ```kotlin class ParentFragment : Fragment() { private val sharedViewModel: SharedViewModel by activityViewModels() } class ChildFragment : Fragment() { private val sharedViewModel: SharedViewModel by activityViewModels() } ``` In the `SharedViewModel`, I'm using MutableLiveData to hold a list of items: ```kotlin class SharedViewModel : ViewModel() { val itemList = MutableLiveData<List<String>>() init { itemList.value = listOf() } } ``` When I add an item to `itemList` in `ChildFragment` via a button click: ```kotlin addButton.setOnClickListener { val currentList = sharedViewModel.itemList.value ?: listOf() sharedViewModel.itemList.value = currentList + "New Item" } ``` This works fine until I rotate the screen. After rotation, the `itemList` appears to be reset to its initial state, which is an empty list. I checked my fragments and ensured they are correctly retaining the ViewModel instance. I've also tried using `ViewModelProvider(this)` instead of `activityViewModels()` but that led to the same issue. I verified that the ViewModel is not being recreated by adding a log statement in the ViewModel's constructor, and it only logs once as expected. I'm at a loss here and could really use some insight on how to properly retain the ViewModel state across configuration changes. What are your experiences with this? What are your experiences with this? My development environment is macOS. Am I missing something obvious?