Skip to content

Instantly share code, notes, and snippets.

@rozag
Created June 6, 2018 16:45
Show Gist options
  • Save rozag/b0672d49e75c9dd173d55448986d2bd8 to your computer and use it in GitHub Desktop.
Save rozag/b0672d49e75c9dd173d55448986d2bd8 to your computer and use it in GitHub Desktop.
A lifecycle-aware LiveData that sends only new updates after subscription, used for events like navigation and Snackbar messages.
/**
* 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 SingleEventLiveData<T> extends MutableLiveData<T> {
private static final String TAG = "SingleEventLiveData";
private final AtomicBoolean mPending = new AtomicBoolean(false);
@MainThread
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer<T> observer) {
if (hasActiveObservers()) {
MainHelper.log(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);
}
}
});
}
@MainThread
@Override
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment