Android SingleLiveEvent (of LiveData) for UI Event (Kotlin)

June 18, 2019

Why use SingleLiveEvent

Kotlin code for SingleLiveEvent

class SingleLiveEvent<T> : MutableLiveData<T>() {

    private val pending = AtomicBoolean(false)

    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)) {

    override fun setValue(t: T?) {

     * Used for cases where T is Void, to make calls cleaner.
    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.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.