Should life cycle owner be viewLifecycleOwner instead of the fragment instance?
I'm looking at this method from TasksFragment:
private fun setupNavigation() {
viewModel.openTaskEvent.observe(this, EventObserver {
openTaskDetails(it)
})
viewModel.newTaskEvent.observe(this, EventObserver {
navigateToAddNewTask()
})
}
I read here that the life cycle owner should be viewLifecycleOwner instead of the fragment instance, like this:
private fun setupNavigation() {
viewModel.openTaskEvent.observe(viewLifecycleOwner, EventObserver {
openTaskDetails(it)
})
viewModel.newTaskEvent.observe(viewLifecycleOwner, EventObserver {
navigateToAddNewTask()
})
}
The explanation is a bit beyond my understanding, but I think it's because the fragment is never really destroyed on configuration changes, so using it as the life cycle owner results in duplicate observers.
I sent the PR https://github.com/android/architecture-samples/pull/755 here.
The reason is as you said, using viewLifecycleOwner will prevent on resuscribing to the observers, hence preventing them to be notified twice, also, the observers will be removed depending on the lifecycle of the Fragment that suscribes to it.