'MutableLiveData doesn't apply change

    private var number = MutableLiveData(0)

    fun addOne(){
          number.value?.let { it + 1 }
    }
    

I would like to increase my mutableLiveData by 1 all the time using my function. But it still shows 0. What could be wrong there ?



Solution 1:[1]

There are 2 ways to update the value of mutableLiveData
1st is via postValue, if you want to update from background thread

fun addOne(){
    number.postValue(number.value!! + 1)
}

2nd is via setValue, if you want to update from main thread

fun addOne(){
        number.value = number.value!! + 1
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ujjwal Kumar Maharana