Search code examples
androidkotlinandroid-livedatamutablelivedata

How to get result of two mutablelivedata into one


I have two variables in my ViewModel which are controlled by user with buttons. He can decrement or increment value by click on proper button.

val age = MutableLiveData<Int>().apply { value = 0 }

val weight = MutableLiveData<Double>().apply { value = 0.0 }

Now I want enable save button only if value of both variables are greater than 0. How to do that? I thought about create another LiveData variable in ViewModel correctData or observe age and weight variable in Activity in some way, but I need help, because I don't know how to do it.

Thank you for help.

UPDATE

I created MediatorLiveData and it's almost working, almost because it doesn't detect if both sources give true value but if there is any true value.

private val _correctData = MediatorLiveData<Boolean>().apply {
        value = false
        addSource(age) { x -> x?.let { value = x > 0 } }
        addSource(repeats) { x -> x?.let { value = x > 0 } }
    }

Any ideas?


Solution

  • Use another 2 boolean variables that keep track of whether both LiveData has returned true.

    private val _correctData = MediatorLiveData<Boolean>().apply {
            var weightFlag = false
            var ageFlag = false
            value = false
            addSource(age) { x -> x?.let { 
                                ageFlag = x > 0 
                                if (weightFlag && ageFlag) {
                                    value = true
                                }
                            } }
            addSource(weight) { x -> x?.let { 
                                weightFlag = x > 0 
                                if (weightFlag && ageFlag) {
                                    value = true
                                }
                            } }
        }