Last active
September 19, 2018 00:24
-
-
Save markchristopherng/6ec6922b72cdde250a5dc850315b2676 to your computer and use it in GitHub Desktop.
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 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