Skip to content

Instantly share code, notes, and snippets.

@LanderlYoung
Last active August 19, 2021 04:26
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 LanderlYoung/adf40bae16531708d9c4ac4ab0ca0db1 to your computer and use it in GitHub Desktop.
Save LanderlYoung/adf40bae16531708d9c4ac4ab0ca0db1 to your computer and use it in GitHub Desktop.
non sticky LiveData
sealed class LiveEvent<T> : LiveData<T>() {
private var version = 0
/**
* override hashCode and equals,
* so-that, [LiveData.removeObserver] still can work
*/
private inner class ObserverWrapper<T>(
private val other: Observer<T>
) : Observer<T> {
private val registerVersion = version
override fun onChanged(t: T) {
// not "sticky" data
if (version > registerVersion) {
other.onChanged(t)
}
}
override fun hashCode() = other.hashCode()
override fun equals(other: Any?) = this.other == other
}
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
super.observe(owner, ObserverWrapper(observer))
}
override fun observeForever(observer: Observer<in T>) {
super.observeForever(ObserverWrapper(observer))
}
override fun setValue(value: T) {
version++
super.setValue(value)
}
}
class MutableLiveEvent<T> : LiveEvent<T>() {
public override fun setValue(value: T) {
super.setValue(value)
}
public override fun postValue(value: T) {
super.postValue(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment