Home > Back-end >  How to add and remove item in MutableLiveData<ArrayList<String>> and notify the UI in ko
How to add and remove item in MutableLiveData<ArrayList<String>> and notify the UI in ko

Time:12-01

I want to add and remove items in MutableLiveData<ArrayList<String>>. Adding items to the list is working fine and UI is also updating. But removal from array list is not working properly.

@HiltViewModel
class SecondViewModel @Inject constructor() : ViewModel() {

    private var _languagesList : MutableLiveData<ArrayList<String>> = MutableLiveData()
    val languagesList : LiveData<ArrayList<String>> get() = _languagesList

    fun addInList() {
        val a = arrayListOf<String>()
        a.add("c  ")
        _languagesList.postValue(a)
    }

    fun removeFromList() {
        _languagesList.value?.removeAt(0);
        //How to notify UI here
    }

}

CodePudding user response:

Your addInList() code shouldn't work either because it creates a new list each time, losing all the previous items in the list.

It is error prone to use a mutable List like ArrayList as your data type. It would be better to use read-only lists, which you could do like this:

private var _languagesList : MutableLiveData<List<String>> = MutableLiveData()
val languagesList : LiveData<List<String>> get() = _languagesList

fun addInList() {
    val oldList = _languagesList.value.orEmpty()
    _languagesList.value = oldList   "c  " // this is creating a new list
}

fun removeFromList() {
    val oldList = _languagesList.value.orEmpty()
    _languagesList.value = oldList.drop(1) // create new list with first item removed
}

I'm using the .value setter instead of postValue since these functions are probably called synchronously from the main thread.

If you really need the type to be ArrayList (although I can't think of a reason why), then you would need to copy your values into a new ArrayList specifically like this:

private var _languagesList : MutableLiveData<ArrayList<String>> = MutableLiveData()
val languagesList : LiveData<ArrayList<String>> get() = _languagesList

fun addInList() {
    val oldList = _languagesList.value.orEmpty()
    _languagesList.value = ArrayList(oldList).apply {
        add("c  ")
    }
}

fun removeFromList() {
    val oldList = _languagesList.value.orEmpty()
    _languagesList.value = ArrayList(oldList.drop(1))
}

CodePudding user response:

I have found a simple solution for array list.

fun addInList() {
    val oldList = ArrayList(_languagesList.value.orEmpty())
    oldList.add("C  ")
    _languagesList.value = oldList
}

fun removeFromList() {
    val oldList = ArrayList(_languagesList.value.orEmpty())
    oldList.removeLast()
    _languagesList.value = oldList
}
  • Related