How to clear LiveData stored value?

后端 未结 7 1187
暖寄归人
暖寄归人 2021-01-30 02:34

According to LiveData documentation:

The LiveData class provides the following advantages:

...

Always up to date data: If a Li

7条回答
  •  长发绾君心
    2021-01-30 02:58

    You need to use SingleLiveEvent for this case

    class SingleLiveEvent : MutableLiveData() {
    
        private val pending = AtomicBoolean(false)
    
        @MainThread
        override fun observe(owner: LifecycleOwner, observer: Observer) {
    
            if (hasActiveObservers()) {
                Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
            }
    
            // Observe the internal MutableLiveData
            super.observe(owner, Observer { t ->
                if (pending.compareAndSet(true, false)) {
                    observer.onChanged(t)
                }
            })
        }
    
        @MainThread
        override fun setValue(t: T?) {
            pending.set(true)
            super.setValue(t)
        }
    
        /**
         * Used for cases where T is Void, to make calls cleaner.
         */
        @MainThread
        fun call() {
            value = null
        }
    
        companion object {
            private const val TAG = "SingleLiveEvent"
        }
    }
    

    And inside you viewmodel class create object like:

     val snackbarMessage = SingleLiveEvent()
    

提交回复
热议问题