Quer aprender como fazer um objeto LiveData ser modificado através da combinação de dois ou três outros objetos LiveData?
Para isso temos que criar um Transformation Map com multiplos argumentos.
Temos duas formas fazer essa modificação.
val varialvel1 = MutableLiveData()
val varialvel2 = MutableLiveData()
val variavelDependente: LiveData<"TIPO"> = Transformations.map(varialvel1.combine(varialvel2)) {
//fazer qualquer operação para retornar o valor processado
}
ou
val variavelDependente: LiveData<"TIPO"> = Transformations.map(PairLiveData(varialvel1, varialvel2)) {
//fazer qualquer operação para retornar o valor processado
}
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 }
}
}
class TripleLiveData<A, B, C>(first: LiveData<A>, second: LiveData<B>, third: LiveData<C>) : MediatorLiveData<Triple<A?, B?, C?>>() {
init {
addSource(first) { value = Triple(it, second.value, third.value) }
addSource(second) { value = Triple(first.value, it, third.value) }
addSource(third) { value = Triple(first.value, second.value, it) }
}
}
fun <A, B> LiveData<A>.combine(other: LiveData<B>): PairLiveData<A, B> {
return PairLiveData(this, other)
}
fun <A, B, C> LiveData<A>.combine(second: LiveData<B>, third: LiveData<C>): TripleLiveData<A, B, C> {
return TripleLiveData(this, second, third)
}
Para utilizar o Triple é da mesma forma, mas é passado os três parâmetros.
0 comentários