Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements from a list that is used by liveData does not remove any

Android 4.1.2
Kotlin 1.4.21

I have the following live data that I add to, but when it comes to removing it doesn't remove any elements.

val selectedLiveData by lazy { MutableLiveData<List<Core>>() }

I don't want to trigger the observers so I am not assigning the value as I just want to remove a single element from the liveData list and only trigger when adding.

None of the following work

selectedLiveData.value?.toMutableList()?.apply {
    removeAt(0)
}

selectedLiveData.value?.toMutableList()?.apply {
    removeFirst()
}
                
selectedLiveData.value?.toMutableList()?.apply {
     remove(Core)
}

I am adding my elements like this and then assigning the value so the observers to this live data get updated:

selectedLiveData.value = selectedLiveData.value?.toMutableList()?.apply {
      add(core)
}
like image 700
ant2009 Avatar asked Sep 14 '25 13:09

ant2009


1 Answers

What you wanted is

val selectedLiveData = MutableLiveData<List<Core>>(emptyList())

Then

selectedLiveData.value = selectedLiveData.value.toMutableList().apply {
    removeAt(0)
}.toList()
like image 50
EpicPandaForce Avatar answered Sep 16 '25 07:09

EpicPandaForce