Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine the result of 2 LiveData fields into another LiveData field of a different type

I have a ViewModel class with 2 livedata observables (eg a and b) that are both of a nullable type and I want to add a new boolean observable (eg c) that is true whenever both a and b are not null, and false otherwise.

I was recommended to use a LiveData Transformation to achieve this but I'm not quite sure how that would work. With a map transformation, I can only ever transform between a single observer, but I can't add multiple sources.

Then that lead me to looking at representing c as a MediatorLiveData and add a and b as sources but then that relies on the fact that they are all of the same type, so I'm not sure if I can use that either.

What's the idiomatic way to accomplish this?

like image 397
pingOfDoom Avatar asked Oct 28 '25 15:10

pingOfDoom


1 Answers

the recommended approach for kotlin is StateFlow. It is like a liveData but more kotlin idiomatic.

this is an example of combining a String flow with an Int flow into a Boolean flow

class ExampleViewModel() : ViewModel() {
    private val _a = MutableStateFlow<Int>(2)
    val a = _a.asLiveData()
    private val _b = MutableStateFlow<String>("example")
    val b = _b.asLiveData()
    // this will emit a value at each update of either _a or _b
    val c = _a.combine(_b) { a, b -> a > b.length }.asLiveData()
    // this will emit a value at each update of _a
    val d = _a.zip(_b) { a, b -> a > b.length }.asLiveData()
    // this will emit a value at each update of _b
    val e = _b.zip(_a) { b, a -> a > b.length }.asLiveData()
    // this is the same as d
    val f = _a.map { it > _b.value.length }.asLiveData()
}

Learn more here

like image 196
Sinner of the System Avatar answered Oct 30 '25 07:10

Sinner of the System



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!