Live Data with ArrayList not observing (Kotlin)?

Viewed 1729

I am using one of Android Jetpack Component ViewModel + Live data in my project it works fine for me when using normal data such as string and Int but when it comes to arrayList it won't observe anything

Here's my code

class MainActivityModel : ViewModel() {

    private var dataObservable = MutableLiveData<ArrayList<Int>>()

    init {
        dataObservable.value = arrayListOf(1,2,3,4,5)
    }

    fun getInt(): LiveData<ArrayList<Int>> = dataObservable

    fun addInt(i:Int) {
        dataObservable.value!![i] = dataObservable.value!![i].plus(1)
    }
}
2 Answers

A LiveData won't broadcast updates to observers unless its value is completely reassigned with a new value. This does not reassign the value:

dataObservable.value!![i] = dataObservable.value!![i].plus(1)

What it does is retain the existing array, but add an array element. LiveData doesn't notify its observables about that. The actual array object has to be reassigned.

If you want to reassign a new array value and notify all observers, reassign a new array altogether, like this:

dataObservable.value = dataObservable.value!![i].plus(1)

Assigning dataObservable.value will call the LiveData setValue() method, and notify observers of the new value passed to setValue() .

If you modify your complex observable object outside of main thread you need to use postValue

       dataObservable?.value[i] += 1 
       dataObservable.apply { 
                postValue(value)
       }
Related