First of all, since you are not calling observeForever()
, but just calling observe()
in order to observe a livedata from an object that has a lifecycle, you probably don't need to remove the observer – it will be ignored/removed automatically by the system when the subscriber stops being active.
However, if you really need to remove the observer manually for whatever reason, you will have to save your observer into a property. That way, you will later be able to pass the observer as a parameter to the method removeObserver()
:
// Define your observer as a property
private val emailValidObserver = Observer<GenericResponse> { onEmailValidChanged(it) }
...
private fun onEmailValidChanged(emailValidResponse: GenericResponse) {
dismissProgressBar()
if (emailValidResponse != null && emailValidResponse.success) {
findNavController().navigate(R.id.action_navigatesomewhere)
}
}
...
// Observe the livedata with the observer you have defined
viewModel.emailValid.observe(this, emailValidObserver)
...
// Stop observing the livedata
shoppingListName.removeObserver(emailValidObserver)
On the other hand, if at some point you want to remove all the observers associated with your lifecycle instance, you can just call this method:
removeObservers(this)