You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
Describe the bug
Currently all of our fragments use the fragment as the lifecycle owner when subscribing to LiveData objects. This is problematic because:
replaced
with another one, the view hierarchy will be destroyed but the fragment will not be.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?
The text was updated successfully, but these errors were encountered: