discCard
discCard

Reputation: 521

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 ?

Upvotes: 0

Views: 55

Answers (2)

Ujjwal Kumar Maharana
Ujjwal Kumar Maharana

Reputation: 269

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
    }

Upvotes: 0

Mohmmaed-Amleh
Mohmmaed-Amleh

Reputation: 438

you are not change live data value ...you are just get the value : you should

number.value = number.value!! + 1

Upvotes: 1

Related Questions