2020-03-16

2020-03-16  本文已影响0人  c51acacfcd47

publicclassSingleLiveEventextendsMutableLiveData{

privatestaticfinalStringTAG="SingleLiveEvent";

privatefinalAtomicBooleanmPending=newAtomicBoolean(false);

@MainThread

publicvoidobserve(LifecycleOwnerowner,finalObserverobserver) {

if(hasActiveObservers()) {

Log.w(TAG,"Multiple observers registered but only one will be notified of changes.");

        }

//Observe the internal MutableLiveData

super.observe(owner,newObserver() {

@Override

publicvoidonChanged(@NullableTt) {

if(mPending.compareAndSet(true,false)) {

observer.onChanged(t);

                }

            }

        });

    }

@MainThread

publicvoidsetValue(@NullableTt) {

mPending.set(true);

super.setValue(t);

    }

/**

    * Used for cases where T is Void, to make calls cleaner.

*/

@MainThread

publicvoidcall() {

setValue(null);

    }

}

上一篇 下一篇

猜你喜欢

热点阅读