CodexBloom - Programming Q&A Platform

Fragment implementation guide UI after LiveData change in ViewModel during configuration change in Android 14

πŸ‘€ Views: 27 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-24
android livedata viewmodel fragment configuration-changes Kotlin

I'm optimizing some code but I'm sure I'm missing something obvious here, but I'm working on a personal project and I'm working with an scenario where my Fragment does not update the UI when the LiveData from the ViewModel changes, particularly after a configuration change like screen rotation..... I have a simple implementation where I'm observing LiveData but it seems to be losing the observer reference after orientation changes. Here's my setup: In my ViewModel, I have the following LiveData: ```kotlin class MyViewModel : ViewModel() { private val _data = MutableLiveData<String>() val data: LiveData<String> get() = _data fun updateData(newData: String) { _data.value = newData } } ``` In my Fragment, I'm observing this LiveData: ```kotlin class MyFragment : Fragment() { private lateinit var viewModel: MyViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_layout, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this).get(MyViewModel::class.java) viewModel.data.observe(viewLifecycleOwner, { updatedData -> // Assume textView is a TextView in the layout textView.text = updatedData }) } } ``` I initialize the data in `onActivityCreated` like this: ```kotlin viewModel.updateData("Initial Data") ``` The question arises when I rotate the screen; the `Fragment` seems to retain the UI state but does not reflect the updated LiveData. I don’t see any behavior messages, and the observer is set correctly. I've checked that `viewLifecycleOwner` is still valid after the rotation. I suspect that the Fragment is recreating but not properly re-attaching to the ViewModel's LiveData. Is there something more I need to do to ensure that the UI updates correctly after a configuration change? Any tips would be greatly appreciated! How would you solve this? Am I missing something obvious? My team is using Kotlin for this web app.