利用SingleLiveEvent 使 observe#LiveData时只相应一次onChanged操作 SingleLiveEvent 利用 AtomicBoolean (默认为false)进行赋值,当LiveData 进行 setValue时 改变 AtomicBoolean的值(set(true))使用 AtomicBoolean.compareAndSet(true,false)方法, 先进行判断(将set(true)的值与 compareAndSet设置的except值(第一个参数)比较,因为相等所以 将AtomicBoolean值设为false(compa..第二个参数的值) 返回 true ,);当再次进入该页面虽然 LiveData值 并没有改变,仍然触发了 observer方法,但是 由于 AtomicBoolean已经为 false ,但是 except值为 true , 与if 进行判断所以 并不会继续触发 onChanged(T)方法 即只有在 setValue时相应一次onChanged(T)方法。
源码如下:
public class SingleLiveEvent<T> extends MutableLiveData<T> {
private static final String TAG = "SingleLiveEvent";
private final AtomicBoolean mPending = new AtomicBoolean(false);
@MainThread
public void observe(LifecycleOwner owner, final Observer<? super T> observer) {
if (hasActiveObservers()) {
Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
}
// Observe the internal MutableLiveData
super.observe(owner, new Observer<T>() {
@Override
public void onChanged(@Nullable T t) {
if (mPending.compareAndSet(true, false)) { //
observer.onChanged(t);
}
}
});
}
/**
* modify by bzb
* 当 setValue时 mPending.set(true) compareAndSet(true,false) (true(set(true)后的“原值”) == true(except 值))=true -> mPending.set(false(update值)) 所以 再次 observer
* 时 该值为false 所以不会执行 onChanged(t)方法
* @param 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);
}
}
AtomicBoolean的 compareAndSet方法
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(boolean expect, boolean update) {
return U.compareAndSwapInt(this, VALUE,
(expect ? 1 : 0),
(update ? 1 : 0));
}