Home > Net >  MutableLiveData doesn't apply change
MutableLiveData doesn't apply change

Time:02-27

    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 ?

CodePudding user response:

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

number.value = number.value!!   1

CodePudding user response:

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
    }
  • Related