Created
April 24, 2020 11:15
-
-
Save NinoDLC/bd8c154d9920cebd6b2deb8ee05aa97d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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