LiveData remove Observer after first callback

There is a more convenient solution for Kotlin with extensions:

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

This extension permit us to do that:

liveData.observeOnce(this, Observer<Password> {
    if (it != null) {
        // do something
    }
})

So to answer your original question, we can do that:

val livedata = model.getDownloadByContentId(contentId)
livedata.observeOnce((AppCompatActivity) context, Observer<T> {
    if (it != null) {
        DownloadManager.this.downloadManagerListener.onDownloadManagerFailed(null, "this item already exists");
    }
    startDownload();
})

The original source is here: https://code.luasoftware.com/tutorials/android/android-livedata-observe-once-only-kotlin/

Update: @Hakem-Zaied is right, we need to use observe instead of observeForever.

Leave a Comment