Home > OS >  How can i compare between two LiveData values in kotlin
How can i compare between two LiveData values in kotlin

Time:11-20

In this picture i have an error with the 'greater than' , i have two LiveData values _adder.value and _quantity.value, i want to compare between them.

Here's a screen and Here's the error

CodePudding user response:

The live data values are nullables, so you can't do that comparison. From the androidX LiveData java class:

    @Nullable
    public T getValue() {
        Object data = mData;
        if (data != NOT_SET) {
            return (T) data;
        }
        return null;
    }

The @Nullable annotation tells Kotlin that has to make the value nullable. That is why the errors says

Required Int
Found Int?
val adderValue = _adder.value //this is nullable
val quantityValue = _quantity.value //this is nullable

For fixing your problem you have to decide what to do with null.

If you want that null to be equivalent to zero, then:

_adder.value ?: 0 < _quantity.value ?: 0

Or if is null, then nothing should happen, then:

val adderValue = _adder.value ?: return
val quantityValue = _quantity.value ?: return
if (adderValue < quantityValue)

Since you are adding a cupcake I speculate what you want is the following:

val adderValue = _adder.value ?: 0 //no additions before so is ok
val quantityValue = _quantity.value ?: return //null quantity is not ok, error we stop
if (adderValue < quantityValue) {
    _adder.value = adderValue  
}

What you are doing there _adder.value?.plus(1) is not updating the live data value.

CodePudding user response:

Kotlin's equality operators (== and !=) can handle nulls, while the order comparison operators (<, <=, >, >=) can't.

You have to check the nullability before doing the comparison.

You may also use another value if the live data is null (like 0) using the Elvis operator, but I won't suggest this solution, because the null value is not the same as the zero value.

  • Related