Notify Observer when item is added to List of LiveData

后端 未结 8 1202
一个人的身影
一个人的身影 2020-12-07 20:21

I need to get an Observer event when the item is added to the List of LiveData. But as far as I understand the event receives only when I replace the old list with a new one

8条回答
  •  借酒劲吻你
    2020-12-07 20:47

    How about this?

    public class ListLiveData extends LiveData> {
        public void addAll(List items) {
            if (getValue() != null && items != null) {
                getValue().addAll(items);
                setValue(getValue());
            }
        }
    
        public void clear() {
            if (getValue() != null) {
                getValue().clear();
                setValue(getValue());
            }
        }
    
        @Override public void setValue(List value) {
            super.setValue(value);
        }
    
        @Nullable @Override public List getValue() {
            return super.getValue();
        }
    }
    
    // add changed listener
        mMessageList.observe(mActivity, new Observer() {
            @Override public void onChanged(@Nullable Object o) {
                notifyDataSetChanged();
            }
        });
    

提交回复
热议问题