Created
March 4, 2022 00:58
-
-
Save Jeff-Soares/138f8f3a6697e37fe735f34b4c3e1870 to your computer and use it in GitHub Desktop.
A lifecycle-aware observable that sends only new updates after subscription, used for events like navigation and Snackbar messages.
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
class SingleLiveEvent<T> : MutableLiveData<T>() { | |
private val mPending = AtomicBoolean(false) | |
@MainThread | |
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { | |
if (hasActiveObservers()) { | |
Log.w(TAG, "Multiple observers registered but only one will be notified of changes.") | |
} | |
super.observe(owner, Observer<T> { t -> | |
if (mPending.compareAndSet(true, false)) { | |
observer.onChanged(t) | |
} | |
}) | |
} | |
@MainThread | |
override fun setValue(@Nullable t: T?) { | |
mPending.set(true) | |
super.setValue(t) | |
} | |
@MainThread | |
fun call() { | |
value = null | |
} | |
companion object { | |
private const val TAG = "SingleLiveEvent" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment