Created
August 9, 2019 07:39
-
-
Save kishansinhparmar/e4eb27cd13d4a13c28d5cc5691339700 to your computer and use it in GitHub Desktop.
This file contains 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 { | |
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