Reputation: 2607
I got ViewModel
that receive one item and it need to update list in the recycler. I made it work but i am wondering if there is a cleaner solution. Im asking about addItem
and deleteItem
functions
class MainViewModel(private val app: Application) : AndroidViewModel(app) {
private val roomManager: RoomManager = RoomManagerImpl(app)
private val prefsManager: PrefsManager = PrefsManagerImpl(app)
private val todoItemList: MutableLiveData<List<ToDoItem>> = MutableLiveData()
val todoItemListResult: LiveData<List<ToDoItem>> = todoItemList
fun getAllItems() {
val result = roomManager.getAllItems()
todoItemList.postValue(result)
}
fun addItem(item: ToDoItem) {
val list = todoItemList.value?.let {
it.toMutableList() + item
}
todoItemList.postValue(list)
}
fun updateItem(item: ToDoItem) {
roomManager.editItem(item)
}
fun deleteItem(item: ToDoItem) {
val list = todoItemList.value?.let {
it.toMutableList() - item
}
todoItemList.postValue(list)
roomManager.deleteItem(item)
}
}
And here is activity observer
viewModel.todoItemListResult.observe(this, Observer {
data = it
adapter.updateList(it)
screenDataValidation(it)
})
Upvotes: 0
Views: 45
Reputation: 329
Why do You use
todoItemList.postValue(list)
The postValue() method is slower because of synchronization costs and not needed in updating from main thread. Just use value.
In the deleteItem method You set data in room and in addItem not?
In other things, Your code seems ok, if You want to avoid unnecessary structures, I would recommend write like that:
if (list.isNullOrEmpty())
return
todoItemList.value = todoItemList.value + item
roomManager.add(item)
Upvotes: 1