Skip to content

Instantly share code, notes, and snippets.

@markchristopherng
Last active September 19, 2018 00:24
Show Gist options
  • Save markchristopherng/6ec6922b72cdde250a5dc850315b2676 to your computer and use it in GitHub Desktop.
Save markchristopherng/6ec6922b72cdde250a5dc850315b2676 to your computer and use it in GitHub Desktop.
class EventLiveData<T> : MutableLiveData<T>() {
private var isRead: AtomicBoolean = AtomicBoolean(false)
/**
* ensure the event is non-null and can only been seen once
*/
fun observeEvent(owner: LifecycleOwner, observer: Observer<T>) {
super.observe(owner, Observer {
if (it != null && isRead.compareAndSet(false, true)) {
observer.onChanged(it)
}
})
}
/**
* re-implemented post method, as the original implementation may swallow date changes
* by ignored all data before last [postValue] call
*/
override fun postValue(value: T) {
if (Thread.currentThread() == Looper.getMainLooper().thread) {
setValue(value)
} else {
Handler(Looper.getMainLooper()).post { setValue(value) }
}
}
override fun setValue(value: T) {
isRead.set(false)
super.setValue(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment