Android LiveData prevent receive the last value on observe

后端 未结 12 1297
自闭症患者
自闭症患者 2020-11-27 04:41

Is it possible to prevent LiveData receive the last value when start observing? I am considering to use LiveData as events.

For example eve

12条回答
  •  一生所求
    2020-11-27 05:34

    I`m using this EventWraper class from Google Samples inside MutableLiveData

    /**
     * Used as a wrapper for data that is exposed via a LiveData that represents an event.
     */
    public class Event {
    
        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;
        }
    }
    

    In ViewModel :

     /** expose Save LiveData Event */
     public void newSaveEvent() {
        saveEvent.setValue(new Event<>(true));
     }
    
     private final MutableLiveData> saveEvent = new MutableLiveData<>();
    
     LiveData> onSaveEvent() {
        return saveEvent;
     }
    

    In Activity/Fragment

    mViewModel
        .onSaveEvent()
        .observe(
            getViewLifecycleOwner(),
            booleanEvent -> {
              if (booleanEvent != null)
                final Boolean shouldSave = booleanEvent.getContentIfNotHandled();
                if (shouldSave != null && shouldSave) saveData();
              }
            });
    

提交回复
热议问题