ant2009
ant2009

Reputation: 22526

adding to a list that is contained in livedata and adding elements to that list

adding to a list that is contained in livedata and adding elements to that list

val resourcesLiveData by lazy { MutableLiveData<List<File>>() }
    

I thought this should work as my LiveData is a list of files and I just want to add elements to it. But the value of live data is always an empty list. The res is the different file resources I am trying to add

resourceLiveData.value?.toMutableList()?.add(res) 
                

So I tried it more expicity using this version but the list is still empty

val listOfRes = resourceLiveData.value ?: emptyList()
listOfRes.toMutableList().add(res)
resourceLiveData.value = listOfRes.toList()
                

Can anyone see if I am doing something wrong.

Just want to add to the list that is contained in the value

Upvotes: 0

Views: 968

Answers (2)

Rajan Kali
Rajan Kali

Reputation: 12953

Agree to @KeyserSoze answer, if you have to use only List then you can do below

resourceLiveData.value = resourceLiveData.value?.toMutableList()?.apply { add(res) }?: emptyList()

Upvotes: 1

Xid
Xid

Reputation: 4951

You are creating a new object by calling toMutableList() instead of updating the original.

Change your LiveData type to MutableList:

val resourcesLiveData by lazy { MutableLiveData<MutableList<File>>() }

Then, update the value accordingly:

resourceLiveData.value?.add(res) 

Upvotes: 1

Related Questions