Skip to content

Instantly share code, notes, and snippets.

@kishansinhparmar
Created August 9, 2019 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kishansinhparmar/e4eb27cd13d4a13c28d5cc5691339700 to your computer and use it in GitHub Desktop.
Save kishansinhparmar/e4eb27cd13d4a13c28d5cc5691339700 to your computer and use it in GitHub Desktop.
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 {
if (mPending.compareAndSet(true, false)) {
observer.onChanged(it)
}
})
}
@MainThread
override fun setValue(@Nullable t: T?) {
mPending.set(true)
super.setValue(t)
}
/**
* Used for cases where T is Void, to make calls cleaner.
*/
@MainThread
fun call() {
setValue(null)
}
companion object {
private val TAG = "SingleLiveEvent"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment