Android Livedata Observe Once Only (Kotlin)

April 1, 2019
val liveData = viewModel.getPassword(id)
liveData.observe(this, object: Observer<Password> {
    override fun onChanged(password: Password?) {
        liveData.removeObserver(this)
    }
})

You can write a Kotlin Extensions to create a convinience method of observeOnce.

fun <T> LiveData<T>.observeOnce(lifecycleOwner: LifecycleOwner, observer: Observer<T>) {
    observe(lifecycleOwner, object : Observer<T> {
        override fun onChanged(t: T?) {
            observer.onChanged(t)
            removeObserver(this)
        }
    })

    /*
    observeForever(object : Observer<T> {
        override fun onChanged(t: T?) {
            observer.onChanged(t)
            removeObserver(this)
        }
    })
     */
}
liveData.observeOnce(this, Observer<Password> {
    if (it != null) {
        // do something
    }
})
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.