androidkotlinmvvmandroid-viewmodelmutablelivedata

How to add and remove item in MutableLiveData<ArrayList<String>> and notify the UI in kotlin


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
    }

}

Solution

  • I've found a simple solution if you want remove a selected item too

     fun addInList() {
        val oldList = _listChips.value.orEmpty()
        _listChips.value = ArrayList(oldList).apply {
            add("c++")
        }
        val oldList = ArrayList(_languagesList.value.orEmpty())
        oldList.add("C++")
        _languagesList.value = oldList
    }
    
    fun removeFromList() {
        val oldList = _listChips.value.orEmpty()
        _listChips.value =
            ArrayList(oldList.filterIndexed { index, _ -> index != oldList.indexOf("C++") })
    }