Bob Redity
Bob Redity

Reputation: 621

How can I observe two LiveData and use results together. How to implement MediatorLiveData?

I got to live data observer and one function that need results from both observers. How to make this function calls when both observers receives data? Not code looks like this

firstViewModel.dataOne.observe(viewLifecycleOwner) {
        secondViewModel.dataTwo.observe(viewLifecycleOwner) { dataTwoResult ->
            setAssociateInfo(dataTwoResult, it) // <--- send two parameters from to observers together
        }
    }

Upvotes: 1

Views: 3787

Answers (2)

Mark
Mark

Reputation: 9929

Something like this should work (all code untested but should work fine) :

val a : MutableLiveData<Int> = MutableLiveData(1)
val b : MutableLiveData<String> = MutableLiveData("B")

val c : MediatorLiveData<Pair<Int?, String?>> = MediatorLiveData<Pair<Int?, String?>>().apply {
    addSource(a) { value = Pair(it, b.value) }
    addSource(b) { value = Pair(a.value, it) }
}

c.observe(lco, Observer {  })

This will work akin to combine latest.

As a simple extension function :

fun <T, S> LiveData<T?>.combineWith(other: LiveData<S?>): LiveData<Pair<T?, S?>> =
    MediatorLiveData<Pair<T?, S?>>().apply {
        addSource(this@combineWith) { value = Pair(it, other.value) }
        addSource(other) { value = Pair([email protected], it) }
    }

Usage :

firstViewModel.dataOne.combineWith(secondViewModel.dataTwo)
              .observe(viewLifecycowner, Observer { latestPairResult ->  }

Upvotes: 5

Ananiya J. Kesto
Ananiya J. Kesto

Reputation: 1364

In my approach you can store the data inside data class instead of creating separate variable and observe them Like

//data class
//you can declare the data type to be stored
data class Datas(val data0: String , val data1: String)
//
//...
//inside view model
private val _datas = MutableLiveData<Datas> ()
val datas: LiveData = _datas

init {
    viewmodelscope.launch {
         //store the changes here
        val value = Datas("value1","value2")
        _datas.value = value
   }
}

And finally you can observe it like

myviewmode.datas.observe(lifecycle){
      setAssociateInfo(it.data0, it.data1)
}

Upvotes: 0

Related Questions