Fragment Lifecycle guide: ViewModel Not Retaining Data After Orientation Change in Android 14
I'm attempting to set up I'm trying to configure I'm having an scenario with my Fragment lifecycle in Android 14 where my ViewModel seems to be losing its data after an orientation change. I'm using ViewModel with a LiveData object to hold a list of items fetched from an API. The initial data load works fine, but once I rotate the device, the ViewModel is recreated and is not retaining the data as expected. Here's the relevant code from my ViewModel: ```kotlin class MyViewModel : ViewModel() { private val _items = MutableLiveData<List<Item>>() val items: LiveData<List<Item>> get() = _items fun fetchItems() { // Simulate a network call _items.value = listOf(Item("Item 1"), Item("Item 2")) } } ``` And in my Fragment, I observe the items 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) viewModel.fetchItems() viewModel.items.observe(viewLifecycleOwner, Observer { items -> // Update UI with items }) return inflater.inflate(R.layout.fragment_my, container, false) } } ``` The question seems to stem from the fact that `fetchItems()` gets called every time the Fragment is created, leading to overwriting the LiveData values. I tried checking the `savedInstanceState` to conditionally call `fetchItems()`, but I'm not sure if that's the right way to handle this. Here's what I attempted: 1. Used `savedInstanceState` in `onCreateView` to prevent refetching when the Fragment is re-created but it still doesn't hold the data as expected. 2. Tried moving the data fetching logic to `onViewCreated`, but the behavior is the same. I'm also using Hilt for dependency injection with the ViewModel. The LiveData does seem to be observed properly, but it just resets after the rotation. The logcat shows no errors, and I see the ViewModel being recreated each time. Any advice on correctly retaining the ViewModel data across configuration changes would be greatly appreciated! I'd love to hear your thoughts on this. I'm working on a CLI tool that needs to handle this. Any examples would be super helpful.