Fragments create new instances of Observers after onActivityCreated
See original GitHub issueFirst of all I want to say thanks for the three samples which enlighten working with these new components significantly, looking at the code there is a lot to learn.
After trying to create a project, making use of the new arch components, I noticed that one of my Fragments received more and more events from LiveData within the Observer code after navigating back and forth in the UI.
This happens due to the Fragment instance being retained and popped back from the stack after “back” navigation.
In these examples typically in onActivityCreated
LiveData is observed and a new Observer is created. In order to solve recreating new Observers, checking if onActivityCreated
has been called on the instance of Fragment before seems to be the goto solution for the moment.
@yigit how would you go about this? check if savedInstanceState is null and then create Observers? I also noticed that declaring the Observers as final fields seems to solve the issue as well, meaning that registering the same Observer instance several times seems to be fine, is this something you would recommend?
Thanks a lot and keep up the good work! Manuel
UPDATE 12 Oct 2019
using viewLifecycleOwner
as LifecycleOwner as proposed seems to solve my issue. Typically what I do now is the following:
class MainFragment : Fragment() {
// ... declare viewmodel lazy
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel.liveData.observe(viewLifecycleOwner, Observer { item ->
// ... code that deals with item / state goes here
})
}
//...
}
Issue Analytics
- State:
- Created 6 years ago
- Reactions:29
- Comments:57 (11 by maintainers)
Top GitHub Comments
After some thinking I realized fragments actually provide 2 distinct lifecycles:
My proposed solution is to create a fragment which allows accessing the lifecycle of the current view hierarchy in addition to its own.
It can be used to register an observer in
onActivityCreated()
that will be properly unregistered inonDestroyView()
automatically:When the fragment is detached and re-attached, the last result will be pushed to the new view hierarchy automatically as expected.
@yigit Do you think this is the right approach to solve the problem in the official library?
The proper fix is to use
Fragment.getViewLifecycleOwner()
which is already part of AndroidX.