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