CodexBloom - Programming Q&A Platform

Issues with LiveData not triggering observers when using custom MediatorLiveData in Android ViewModel

πŸ‘€ Views: 37 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-17
android livedata viewmodel mediatorlivedata Kotlin

I'm encountering a frustrating issue with my `ViewModel` where I have a `MediatorLiveData` set up to combine two `LiveData` sources, but the observers are not being triggered as expected when one of the sources updates... I’ve set it up like this: ```kotlin class MyViewModel : ViewModel() { private val liveData1: MutableLiveData<String> = MutableLiveData() private val liveData2: MutableLiveData<Int> = MutableLiveData() val combinedData: MediatorLiveData<String> = MediatorLiveData<String>().apply { addSource(liveData1) { value = "Data1: $it, Data2: ${liveData2.value}" } addSource(liveData2) { value = "Data1: ${liveData1.value}, Data2: $it" } } } ``` In my fragment, I observe the `combinedData` like this: ```kotlin viewModel.combinedData.observe(viewLifecycleOwner) { combinedValue -> Log.d("CombinedData", combinedValue) } ``` However, when I update either `liveData1` or `liveData2`, the observer for `combinedData` doesn't get notified. I’ve tried manually setting a value to `combinedData` after updating `liveData1`, and it works, but I need the automatic updates. I also verified that both `liveData1` and `liveData2` are indeed changing as expected. Here’s how I update `liveData1`: ```kotlin viewModel.liveData1.value = "Hello" ``` And for `liveData2`: ```kotlin viewModel.liveData2.value = 42 ``` I'm using AndroidX lifecycle components version 2.4.0, and I've ensured that I'm not holding on to any references that could cause memory leaks. Could there be an issue with the way the `MediatorLiveData` is set up, or is there something else I might be overlooking? Any help would be appreciated! What am I doing wrong?