2

I have 2 MutableLiveData. I need to perform a task only when values are returned from both the MutableLiveData. In case of 2 LiveData, we can use MediatorLiveData to do the same. In my case, I am using MutableLiveData and it requires LiveData instead of MutableLiveData.

Now how I perform a task only when values from both the MutableLiveData are returned?

Ankush Kapoor
  • 365
  • 3
  • 13

1 Answers1

0

You can still use MediatorLiveData for this since MutableLiveData extends from LiveData. Take a look at this link for Marek Kondracki's answer How to combine two live data one after the other?:

val profile = MutableLiveData<ProfileData>()

val user = MutableLiveData<CurrentUser>()

val title = profile.combineWith(user) { profile, user ->
    "${profile.job} ${user.name}"
}

fun <T, K, R> LiveData<T>.combineWith(
    liveData: LiveData<K>,
    block: (T?, K?) -> R
): LiveData<R> {
    val result = MediatorLiveData<R>()
    result.addSource(this) {
        result.value = block.invoke(this.value, liveData.value)
    }
    result.addSource(liveData) {
        result.value = block.invoke(this.value, liveData.value)
    }
    return result
}
Christilyn Arjona
  • 2,173
  • 3
  • 13
  • 20