Skip to content

Instantly share code, notes, and snippets.

@NinoDLC
Created April 24, 2020 11:15
Show Gist options
  • Save NinoDLC/bd8c154d9920cebd6b2deb8ee05aa97d to your computer and use it in GitHub Desktop.
Save NinoDLC/bd8c154d9920cebd6b2deb8ee05aa97d to your computer and use it in GitHub Desktop.
import android.util.Log;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import java.util.concurrent.atomic.AtomicBoolean;
public class SingleLiveEvent<T> extends MutableLiveData<T> {
private final AtomicBoolean pending = new AtomicBoolean(false);
@MainThread
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
if (hasActiveObservers()) {
Log.w("SingleLiveEvent", "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(T t) {
if (pending.compareAndSet(true, false)) {
observer.onChanged(t);
}
}
});
}
@MainThread
@Override
public void setValue(T t) {
pending.set(true);
super.setValue(t);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment