1

I have two livedatas startedAt & finishedAt and want to use them in a transformation that depend on both these values...i tried combine them using mediatorliveData

    fun <A, B> LiveData<A>.combine(other: LiveData<B>): PairLiveData<A, B> {
    return PairLiveData(this, other)
}

class PairLiveData<A, B>(first: LiveData<A>, second: LiveData<B>) : MediatorLiveData<Pair<A?, B?>>() {
    init {
        addSource(first) { value = it to second.value }
        addSource(second) { value = first.value to it }
    }
}

and observe them

  val automaticActivities = Transformations.map(startedAt.combine(finishedAt)) {
Log.v("checkindex",index.toString()+"    "+it.first?.size+"      "+it.second?.size)
 }

but this doesn't work as expected as finishedAt returns null before it get its required value ,

debugged rsult :

V/checkindex: 0 1 null

V/checkindex: 0 1 1

will it be a good idea to use a transformation inside a transformation ? ex:

val automaticActivities = Transformations.map(startedAt) {
   val finishedAt  = Transformations.map(finishedAt){
  }
}
Adam Arold
  • 29,285
  • 22
  • 112
  • 207
joghm
  • 569
  • 3
  • 20
  • 1
    You should prevent your mediator from emitting invalid value in the first place. Check if both source values are not null instead of triggering value update unconditionally. – Pawel Oct 13 '20 at 23:04
  • that works fine, but what do you think is the best approach, mediatorlivedata or nested transformation ? both works well for me and give the same result – joghm Oct 14 '20 at 09:57
  • 1
    Transformations are actually mediator livedatas too, by nesting them you're creating multiple instances of it. – Pawel Oct 14 '20 at 10:25

0 Answers0