CodexBloom - Programming Q&A Platform

Unexpected NullPointerException when using LiveData with MediatorLiveData in Android 14

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

I've encountered a strange issue with I'm stuck trying to I've been researching this but I'm working with a `NullPointerException` when trying to use `MediatorLiveData` to combine multiple `LiveData` sources in my Android 14 application. I have two `LiveData` sources: one for user data and another for settings. When either of these `LiveData` objects emits a new value, I expect my `MediatorLiveData` to update accordingly. However, I'm getting a crash with the following stack trace: ``` java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object androidx.lifecycle.LiveData.getValue()' on a null object reference ``` Here’s a simplified version of my code: ```kotlin class MyViewModel : ViewModel() { private val userLiveData = MutableLiveData<User>() private val settingsLiveData = MutableLiveData<Settings>() private val combinedLiveData = MediatorLiveData<Pair<User, Settings>>() init { combinedLiveData.addSource(userLiveData) { user -> val settings = settingsLiveData.value if (user != null && settings != null) { combinedLiveData.value = Pair(user, settings) } } combinedLiveData.addSource(settingsLiveData) { settings -> val user = userLiveData.value if (user != null && settings != null) { combinedLiveData.value = Pair(user, settings) } } } } ``` I've ensured that both `userLiveData` and `settingsLiveData` are initialized before they are observed. Despite this, the `NullPointerException` occurs when the `MediatorLiveData` tries to access the value of `settingsLiveData` or `userLiveData` in the callback. I've also tried adding a check to ensure that both values are not null before creating the pair, but it seems like the behavior still continues. Is there something I'm missing in the way `MediatorLiveData` works, or a specific best practice I should be following to avoid this scenario? Any insights or suggestions would be greatly appreciated! What's the correct way to implement this? This is my first time working with Kotlin 3.10. Could this be a known issue? This issue appeared after updating to Kotlin LTS. I'm open to any suggestions. This is for a CLI tool running on macOS. Any feedback is welcome!