Why use SingleLiveEvent
- For propogation of UI event, such as Click. E.g. Handle RecyclerView Click Event With SingleLiveEvent.
- Why not use
LiveData
? BecauseLiveData
will trigger again upon configuation change / screen rotation. We want to handle UI event such as click once only. - SingleLiveEvent would not be part of support library.
Kotlin code for SingleLiveEvent
class SingleLiveEvent<T> : MutableLiveData<T>() { private val pending = AtomicBoolean(false) @MainThread override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { if (hasActiveObservers()) { Log.w(TAG, "Multiple observers registered but only one will be notified of changes.") } // Observe the internal MutableLiveData super.observe(owner, Observer<T> { t -> if (pending.compareAndSet(true, false)) { observer.onChanged(t) } }) } @MainThread override fun setValue(t: T?) { pending.set(true) super.setValue(t) } /** * Used for cases where T is Void, to make calls cleaner. */ @MainThread fun call() { value = null } companion object { private const val TAG = "SingleLiveEvent" }}
NOTE: The disadvantage of SingleLiveEvent is that there can only be one observer. There is a solution to support multiple observers, which I haven’t tried yet.