I want to implement swipe to delete functionality in a RecyclerView which is populated with data from an API.
There is a ViewModel
class and data is fetched from API to a allOrders: MutableLiveData<MutableList<ModelClass>>
in ViewModel. The observer in Fragment updates the RecyclerView Adapter on LiveData change:
viewModel.allOrders.observe(viewLifecycleOwner, Observer {
adapter.submitList(it)
})
I want to delete the swiped item in RecyclerView from allOrders: MutableLiveData<MutableList<ModelClass>>
, so this is the function to do that in ViewModel class:
fun deleteItem(index: Int) {
_allOrders.value?.removeAt(index)
}
But removing an item from MutableLiveData<MutableList>
doesn't even notify the observer.
What is the best practice for implementing such a functionality using ViewModel and LiveData in Kotlin?
UPDATE
I change deletItem function to this:
fun deleteItem(index: Int) {
_allOrders.value = _allOrders.value?.also { list ->
list.removeAt(index)
}
Now the observer is being notified, but adapter.submitList(it)
doesn't change RecyclerView to new list. Scrolling the RecyclerView throw IndexOutOfBoundsException
.
The adapter class looks like this one in codeslab example