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

Jun 18, 2019

Why use SingleLiveEvent

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.