Android LiveData prevent receive the last value on observe

后端 未结 12 1308
自闭症患者
自闭症患者 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:15

    Even i had the same requirement. I have achieved this by extending the MutableLiveData

    package com.idroidz.android.ion.util;    
    import android.arch.lifecycle.LifecycleOwner;
    import android.arch.lifecycle.MutableLiveData;
    import android.arch.lifecycle.Observer;
    import android.support.annotation.MainThread;
    import android.support.annotation.Nullable;
    
    import java.util.concurrent.atomic.AtomicBoolean;
    
    public class VolatileMutableLiveData extends MutableLiveData {
    
    
        private final AtomicBoolean mPending = new AtomicBoolean(false);
    
        @MainThread
        public void observe(LifecycleOwner owner, final Observer observer) {
            // Observe the internal MutableLiveData
            mPending.set(false);
            super.observe(owner, new Observer() {
                @Override
                public void onChanged(@Nullable T t) {
                    if (mPending.get()) {
                        observer.onChanged(t);
                    }
                }
            });
        }
    
        @MainThread
        public void setValue(@Nullable T t) {
            mPending.set(true);
            super.setValue(t);
        }
    
        /**
         * Used for cases where T is Void, to make calls cleaner.
         */
        @MainThread
        public void call() {
            setValue(null);
        }
    
        public void callFromThread() {
            super.postValue(null);
        }
    }
    

提交回复
热议问题