Skip to content

Instantly share code, notes, and snippets.

@Jeff-Soares
Created March 4, 2022 00:58
Show Gist options
  • Save Jeff-Soares/138f8f3a6697e37fe735f34b4c3e1870 to your computer and use it in GitHub Desktop.
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.
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