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
{{ message }}
This repository was archived by the owner on Jan 10, 2025. It is now read-only.
First 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
})
}
//...
}
kazume, bogerchan, lo-g, jenzz, pavelannin and 24 more