CodexBloom - Programming Q&A Platform

Trouble with LiveData Observers Not Triggering After Configuration Changes in Android 14 with ViewModel

👀 Views: 85 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
android livedata viewmodel fragment kotlin

I've searched everywhere and can't find a clear answer. I'm facing an issue where my LiveData observers aren't being triggered after a configuration change (like screen rotation) in my Android 14 application. I have a ViewModel with a MutableLiveData that is supposed to update the UI based on the data changes, but after a configuration change, the observer does not get called. Here's a simplified version of my ViewModel setup: ```kotlin class MyViewModel : ViewModel() { private val _data = MutableLiveData<String>() val data: LiveData<String> get() = _data fun updateData(newData: String) { _data.value = newData } } ``` And in my Fragment, I observe the LiveData 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) return inflater.inflate(R.layout.fragment_my, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.data.observe(viewLifecycleOwner, Observer { newData -> // Update UI with newData textView.text = newData }) } } ``` I am manually updating the LiveData with `viewModel.updateData("New Value")`, but after the screen rotates, the UI does not reflect the new data. I confirmed that `updateData` is being called, but the observer in the Fragment doesn't get triggered after the rotation. I tried using `setRetainInstance(true)` in the Fragment, but that didn't help. I've also ensured that my Fragment's lifecycle is correctly managed with the `viewLifecycleOwner`. The only error message I see in the logcat is `java.lang.IllegalStateException: LifecycleOwner has been destroyed` when I quickly switch between activities. I suspect it might be related to how LiveData is managing its observers post-configuration change. Any insights or suggestions on how to resolve this issue would be greatly appreciated! Thanks in advance!