Last active
August 19, 2021 04:26
-
-
Save LanderlYoung/adf40bae16531708d9c4ac4ab0ca0db1 to your computer and use it in GitHub Desktop.
non sticky LiveData
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
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