从 LiveData 插入(或删除)单个列表项

Che*_*eng 7 android android-livedata android-architecture-components

我想知道,从 中插入(或删除)单个List项目有哪些常见做法LiveData

目前,这就是我打算做的。

我有以下 LiveData

LiveData<List<Animal>> animalListLiveData;
Run Code Online (Sandbox Code Playgroud)

这就是我计划观察它的方式。

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);
});
Run Code Online (Sandbox Code Playgroud)

这就是我要插入单个项目的方式 LiveData

animalListLiveData.getValue().add(newAnimal);
// Inform observer.
animalListLiveData.setValue(animalListLiveData.getValue())
Run Code Online (Sandbox Code Playgroud)

我觉得我的方法对于这样一个简单的更新操作来说太过分了。如果List是巨大的,DiffUtil需要扫描整个List.

其他开发人员和我有同样的感觉。https://github.com/googlesamples/android-architecture-components/issues/135

到目前为止没有提出好的解决方案。

我想知道,你有没有发现任何好的做法(模式),从 中插入(或删除)单个List项目LiveData

Kno*_*sos 5

如果您确切知道更改的位置,例如在新项目按时间顺序出现的情况下,您可以避免手动向适配器报告更改。

如果没有,您需要以某种方式让适配器知道哪些项目已更改。

最后是一天,这些是您的选择:

如果插入和删除是确定性的,则可以直接通知适配器。不需要中间人。

如果没有,你有两个选择。通知适配器整个数据集已更改或检查每个条目以验证位置 (DiffUtil)。

作为旁注,您应该在观察者之外设置您的适配器。直接在 onCreate(或类似的)上,使用在类中预定义的空列表。然后,您可以编辑此列表以响应 observable 的更改。