architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

Should life cycle owner be viewLifecycleOwner instead of the fragment instance?

Open dave-kennedy opened this issue 6 years ago • 1 comments

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.

dave-kennedy avatar Sep 24 '19 16:09 dave-kennedy

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.

gastsail avatar Aug 06 '20 21:08 gastsail