android-fragments 为什么在重新创建我的片段时,我的适配器列表LiveData会收到3次通知

eqfvzcg8  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(283)

在下面的代码片段中,我在我的适配器中使用了list.addAll(),当再次访问片段时,我的列表被添加了3次,而不是1次。但是,当片段是新创建的时,这不会发生。
为什么我在我的场景中从LiveData得到了3次通知?是LiveData中的某种通知机制吗?
程式码片段:

public class MyFragment extends Fragment {

   public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        model.getMyList().observe(getViewLifecycleOwner(), list -> {
                   adapter.setItemList(list);

            }
        );
    }

}

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    public  void    setItemList(List<Item> myList){
        itemList.addAll(myList);

    }

}
7dl7o3gd

7dl7o3gd1#

这是LiveData的默认行为,当可观察到附加到LiveData示例时。它将使用LiveData具有的最新值触发。
为了避免这种情况,您必须创建一个 Package 类,它可以验证数据并返回null(如果数据已经被处理)。
下面的解决方案是从谷歌样本。

/**
 * Used as a wrapper for data that is exposed via a LiveData that represents an event.
 */
public class Event<T> {

    private T mContent;

    private boolean hasBeenHandled = false;

    public Event( T content) {
        if (content == null) {
            throw new IllegalArgumentException("null values in Event are not allowed.");
        }
        mContent = content;
    }
    
    @Nullable
    public T getContentIfNotHandled() {
        if (hasBeenHandled) {
            return null;
        } else {
            hasBeenHandled = true;
            return mContent;
        }
    }
    
    public boolean hasBeenHandled() {
        return hasBeenHandled;
    }
}

现在,在viewmodel中,通过将liveData对象 Package 在Event类中来为它赋值。

{yourlist-livedata}.setValue(new Event<List<Item>>({newData}))

在你的可观察性中,像这样检查它,

model.getMyList().observe(getViewLifecycleOwner(), data -> {
               if(data!= null) {
                   val list = data.getContentIfNotHandled()
                   if(list!= null){
                       adapter.setItemList(list);
                   }
               }
        }
    );

遵循上述方法,您将不会得到重复数据的问题。

相关问题