Edit: This question is a bit out of date now that Google has given us the ability to scope ViewModel
to navigation graphs. The better approach (rather
In my case, most of the things I observe are related to the View
s, so I don't need to clear it in case the View
gets destroyed (but not the Fragment
).
In the case I need things like a LiveData
that takes me to another Fragment
(or that does the thing only once), I create a "consuming observer".
It can be done by extending MutableLiveData
:
fun MutableLiveData.observeConsuming(viewLifecycleOwner: LifecycleOwner, function: (T) -> Unit) {
observe(viewLifecycleOwner, Observer {
function(it ?: return@Observer)
value = null
})
}
and as soon as it's observed, it will clear from the LiveData
.
Now you can call it like:
viewModel.navigation.observeConsuming(viewLifecycleOwner) {
startActivity(Intent(this, LoginActivity::class.java))
}