Skip to content

Instantly share code, notes, and snippets.

@cesarferreira
Created April 30, 2018 21:45
Show Gist options
  • Save cesarferreira/5acc0da01aeeef076048404f8132c510 to your computer and use it in GitHub Desktop.
Save cesarferreira/5acc0da01aeeef076048404f8132c510 to your computer and use it in GitHub Desktop.
HybridMutableLiveData
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