一直在使用SingleLiveEvent用的很順手,今日才發現原來SingleLiveEvent不是原生的,是別人寫好extends from MutableLiveData 的物件,稍微來整理一下兩者差異。
相同:用於observer監聽LiveData改變
不同:MutableLiveData所有observe都會收到消息。
SigleLiveData只會通知給他第一個遇見的人。
舉例:
在activity中創立兩個dialog,兩個dialog都在實例化過程中訂閱某條消息,表示收到某條消息後將自己dismiss,如果將該消息放在SingleLiveEvent中發送,那麼就只會有一個dialog 執行dismiss,而如果將該消息放在MutableLiveData中發送,那麼兩個就都會dismiss。
/**
* A lifecycle-aware observable that sends only new updates after subscription, used for events like
* navigation and Snackbar messages.
* <p>
* This avoids a common problem with events: on configuration change (like rotation) an update
* can be emitted if the observer is active. This LiveData only calls the observable if there's an
* explicit call to setValue() or call().
* <p>
* Note that only one observer is going to be notified of changes.
*/
public class SingleLiveEvent<T> extends MutableLiveData<T> {
private static final String TAG = "SingleLiveEvent";
private final AtomicBoolean mPending = new AtomicBoolean(false);
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull 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, 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);
}
}