I was wondering, what are some common practice, to insert (or delete) single List
item from LiveData
?
Currently, here's what I plan to do.
I have the following LiveData
LiveData<List<Animal>> animalListLiveData;
This is how I plan to observe it.
animalListLiveData.observe(this, animalList -> {
if (listView.getAdapter() == null) {
// First time.
ArrayAdapter<String> adapter = new ArrayAdapter<>(..., animalList);
// Assign adapter to ListView
listView.setAdapter(adapter);
} else {
// Update operation.
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new MyDiffUtilCallback(animalList, oldAnimalList));
diffResult.dispatchUpdatesTo(listView.getAdapter());
}
oldAnimalList.clear();
oldAnimalList.addAll(animalList);
});
This is how I'm going to insert a single item into LiveData
animalListLiveData.getValue().add(newAnimal);
// Inform observer.
animalListLiveData.setValue(animalListLiveData.getValue())
I feel that my method is overkill for such a simple update operation. If the List
is huge, DiffUtil
needs to scan through the entire List
.
Other developers have the same feeling as I do. https://github.com/googlesamples/android-architecture-components/issues/135
No good solution suggested so far.
I was wondering, do you discover any good practice (pattern), to insert (or delete) single List
item from LiveData
?
If you know exactly where the changes will be, for example in the case where new items come up chronologically, you can get away with manually reporting changes to the adapter.
If not, you somehow need to let the adapter know which items have changed.
At the end is the day, these are your options:
If inserting and deleting is deterministic, you can notify the adapter directly. No middleman required.
If not, you have two choices. Either notify the adapter that the entire dataset has changed or check each entry to validate positions (DiffUtil).
As a sidenote, you should be setting your adapter outside of the observer. Directly on onCreate (or similar), using an empty List that is predefined in the class. You can then edit this list in response to changes from the observable.