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

Viewed 2057
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)
}
3 Answers

What you wanted is

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

Then

selectedLiveData.value = selectedLiveData.value.toMutableList().apply {
    removeAt(0)
}.toList()

So what are you doing exactly: You create a MutableLiveData with a List of objects. As we know in Kotlin List is immutable, so it's readonly. If you want to add / remove items from a list, you should use MutableList.

If we look the documentation of toMutableList which you are using:

 /**
 * Returns a new [MutableList] filled with all elements of this collection.
 */
public fun <T> Collection<T>.toMutableList(): MutableList<T> {
    return ArrayList(this)
}

So every time you try to remove an item via:

selectedLiveData.value?.toMutableList()

you actually perform that operation on a new MutableList not the original one.

If you want to add / remove I suggest you to use MutableList in your MutableLiveData so you can create something similar to this:

    private val selectedLiveData = MutableLiveData<MutableList<Int>>()

    // Init
    selectedLiveData.value = mutableListOf(100, 200)
    
    // Add items
    selectedLiveData.value?.add(2)
    selectedLiveData.value?.add(10)
    selectedLiveData.value?.add(50)

    // Remove item
    selectedLiveData.value?.remove(2)
selectedLiveData.postValue(selectedLiveData.value.toMutableList().apply {
    removeAt(0)
}.toList())
Related