Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
dave-kennedy opened this issue Sep 24, 2019 · 1 comment

Comments

@dave-kennedy
Copy link

dave-kennedy commented Sep 24, 2019

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.

@gastsail
Copy link

gastsail commented Aug 6, 2020

I sent the PR #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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants