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

refactor: Migrate project to use viewLifecycleOwner in fragments to observe livedata wherever it makes sense #1326

Closed
1 task done
haroldadmin opened this issue Mar 16, 2019 · 2 comments

Comments

@haroldadmin
Copy link
Contributor

Describe the bug
Currently all of our fragments use the fragment as the lifecycle owner when subscribing to LiveData objects. This is problematic because:

  • Subscribe to livedata in onCreateView/onViewCreated/onActivityCreated using fragment as the lifecycle owner
  • This livedata will automatically unsubscribe when the fragment is torn down, as is the nature of livedata.
  • When fragment is replaced with another one, the view hierarchy will be destroyed but the fragment will not be.
  • Return to this fragment: LiveData is subscribed to again because onCreateView/onViewCreated/onActivityCreated is called again, without unsubscribing to the last subscription.
  • Subscribing to ViewModel in methods called before these three can result in NPE because the ViewModel may not have been initialized by then.

This article explains this problem very well

Google added a solution for this in the form a viewLifecycleOwner property, which relates to the view lifecycle of the fragment instead of the actual fragment lifecycle. This means that when the view hierarchy is destroyed, any live data subscriptions will be unsubscribed too.

Additional context
There is excellent discussion regarding this problem on this Github issue: android/architecture-components-samples#47

Would you like to work on the issue?

  • Yes
@AnEnigmaticBug
Copy link
Contributor

Nice observation 👍 ! I also use viewLifecycleOwner in my new projects.

@RotBolt
Copy link

RotBolt commented Mar 19, 2019

Great observation man !!

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

3 participants