Android

记一次LiveData重复触发数据回调

2021-05-25  本文已影响0人  甜瓜旁的长白山

我用的是网上大哥的SingleLiveEvent,完美解决,附源码

public class SingleLiveEventextends MutableLiveData {

private final AtomicBooleanmPending =new AtomicBoolean(false);

    @Override

    public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer observer) {

super.observe(owner, new Observer() {

@Override

            public void onChanged(@Nullable T t) {

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

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);

    }

上一篇下一篇

猜你喜欢

热点阅读