Skip to content

Instantly share code, notes, and snippets.

@hadilq
Created October 19, 2018 17:05
Show Gist options
  • Save hadilq/db57aaa1af461601060b174bb2f0d0f8 to your computer and use it in GitHub Desktop.
Save hadilq/db57aaa1af461601060b174bb2f0d0f8 to your computer and use it in GitHub Desktop.
class SingleLiveEvent<T> : MutableLiveData<T>() {
private val observers = CopyOnWriteArraySet<ObserverWrapper<T>>()
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<T>) {
val wrapper = ObserverWrapper(observer)
observers.add(wrapper)
super.observe(owner, wrapper)
}
override fun removeObservers(owner: LifecycleOwner) {
observers.clear()
super.removeObservers(owner)
}
override fun removeObserver(observer: Observer<T>) {
observers.remove(observer)
super.removeObserver(observer)
}
@MainThread
override fun setValue(t: T?) {
observers.forEach { it.newValue() }
super.setValue(t)
}
/**
* Used for cases where T is Void, to make calls cleaner.
*/
@MainThread
fun call() {
value = null
}
private class ObserverWrapper<T>(private val observer: Observer<T>) : Observer<T> {
private val pending = AtomicBoolean(false)
override fun onChanged(t: T?) {
if (pending.compareAndSet(true, false)) {
observer.onChanged(t)
}
}
fun newValue() {
pending.set(true)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment