Created
October 19, 2018 17:05
-
-
Save hadilq/db57aaa1af461601060b174bb2f0d0f8 to your computer and use it in GitHub Desktop.
This file contains 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 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