I have a MutableLiveData
like this in my view model:
val liveData = MutableLiveData<ArrayList<*>>()
I add the results from an endpoint call to this LiveData
like this:
liveData.value?.addAll(myList)
as far as I know, MutableLiveData
shouldn't notify it's Observer
s unless you do a setValue
or postValue
on it but at this point when my code is run, Observer
s are notified of the change.
How is this possible?
Update:
I came across an even more stranger behavior, this test passes but the list gets printed one time: []
@Test
fun `strange live data behavior`() {
val myLiveData = MutableLiveData<ArrayList<Int>>()
val observer = mock() as Observer<ArrayList<Int>>
myLiveData.observeForever(observer)
myLiveData.observeForever { println(it) }
myLiveData.value = ArrayList()
verify(observer).onChanged(ArrayList())
myLiveData.value?.addAll(listOf(1, 2, 3, 4))
val result = ArrayList<Int>()
result.add(1)
result.add(2)
result.add(3)
result.add(4)
verify(observer).onChanged(result)
}