Search code examples
androidviewmodelandroid-livedata

it doesn't work by using MutableData.value in Android


class CounterViewModel: ViewModel() {

  val count = MutableLiveData<Integer>()

  fun increase() {
      count.value = count.value + 1
  }

  fun decrease() { 

  }
}

and the 'count.value = count.value + 1' doesn't work. why can't i use plus in that code?


Solution

  • count.value is a nullable that is why is not working. Replace it with

      count.value = (count.value ?: 0) + 1
    

    0 is the fallback if value is null