Created
April 30, 2018 21:45
-
-
Save cesarferreira/5acc0da01aeeef076048404f8132c510 to your computer and use it in GitHub Desktop.
HybridMutableLiveData
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
class HybridMutableLiveData<T> : MutableLiveData<T>() { | |
private val pending = AtomicBoolean(false) | |
private val sticky = AtomicBoolean(false) | |
@MainThread | |
override fun observe(owner: LifecycleOwner, observer: Observer<T>) { | |
// Observe the internal MutableLiveData | |
super.observe(owner, Observer { t -> | |
if (sticky.get() || pending.compareAndSet(true, false)) { | |
observer.onChanged(t) | |
} | |
}) | |
} | |
@MainThread | |
override fun setValue(t: T?) { | |
pending.set(true) | |
super.setValue(t) | |
} | |
override fun postValue(value: T) { | |
postValue(value, false) | |
} | |
fun postValue(t: T?, sticky: Boolean = false) { | |
this.sticky.set(sticky) | |
super.postValue(t) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment