android / architecture-components-samples

Samples for Android Architecture Components.
https://d.android.com/arch
Apache License 2.0
23.42k stars 8.29k forks source link

Fragments create new instances of Observers after onActivityCreated #47

Closed nexuscomputing closed 4 years ago

nexuscomputing commented 7 years ago

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
        })
    }
//...
}
brenoptsouza commented 7 years ago

Yup, same happened to me, the two best solutions came across were:

1 - Register your observers in onCreate instead of onActivityCreated. Though I imagine this may create some errors if events are received before the views are created.

2 - Create a helper method - or if you are in Kotlin land, an extension function :) - that removes any observers previously registered to your lifecycle before observing a LiveData again. And then using it instead of LiveData.observe(). My example:

inline fun <T> LiveData<T>.reobserve(owner: LifecycleOwner, crossinline func: (T?) -> (Unit)) { removeObservers(owner) observe(owner, Observer<T> { t -> func(t) }) }

I don't know if this is the best solution either.

yigit commented 7 years ago

This is an oversight on my end, sorry about it. As @brenoptsouza mentioned, there does not seem to be an obvious solution to this. We'll fix this, thanks.

yigit commented 7 years ago

btw, @@brenoptsouza about 1, great news is that it won't be a problem because LiveData callbacks are not called outside onStart-onStop so view will be ready for sure.

TonicArtos commented 7 years ago

The problem arises because the sample code has the fragments injected after Fragment::onCreate is called. So the viewModels can only be fetched after that in Fragment::onActivityCreated. Which causes the problem with observing live data multiple times.

My solution is to do fragment injection on the fragment pre-attached life cycle callback. As this is called multiple times by the framework, I set a flag on the Injectable interface to ensure the injection is only done once.

interface Injectable {
    var injected: Boolean
}

and the injection

fun OpticsPlannerApplication.initDagger() {
    DaggerAppComponent.builder()
            .application(this)
            .build()
            .inject(this)
    registerActivityLifecycleCallbacks {
        onActivityCreated { activity, _ -> activity.inject() }
    }
}

private fun Activity.inject() {
    if (this is HasSupportFragmentInjector) AndroidInjection.inject(this)
    if (this is FragmentActivity) registerFragmentLifeCycleCallbacks(recursive = true) {
        onFragmentPreAttached { _, fragment, _ ->
            fragment.inject()
        }
    }
}

private fun Fragment.inject() {
    if (this is Injectable && !injected) {
        AndroidSupportInjection.inject(this)
        injected = true
    }
}
cbeyls commented 7 years ago

Newest version of the support library (26.0.0-beta2) has FragmentLifecycleCallbacks.onFragmentPreCreated(). Once stable and released this will be the best place to inject the fragments.

yigit commented 7 years ago

We can move the injection to onFragmentPreAttached so we don't need beta2. On the other hand, a part of the problem is the conflict w/ data-binding. When initialized w/ a retained view, data binding has no way of recovering its values. This is not even feasible since every variable needs to be Parcelable for that to work. So data binding just goes and sets whatever values it has. (it could avoid setting but that would break callbacks which may require actual values)

When data binding starts supporting LiveData as input, we can start passing the ViewModel to avoid these issues.

Until then, if we start observing in onCreate, when fragment's view is recreated (when it goes into backstack and comes back), we have to update the binding from the ViewModel manually. This is necessary because LiveData will not call the observers in this case because it already delivered the last result to that observer. We may also have a mod that will always call the LiveData callback on onStart even if it has the latest value. That is actually the fundamental problem here. Lifecycles does not have a way to know the views accessed by the callback is recreated.

This is annoying yet there is no easy solution for that until data binding supports LiveData.

Btw, this is still a tricky case to handle even w/o data binding, to be able to handle callbacks that requires non-parcelable instances. (e.g. clicking on an Entity to save it, you need the Entity).

Of course, another solution is to keep the views around when onDestroyView is called but that will increase the memory consumption so not desired.

Btw, on a side note, current state does not have any efficiency problems since data binding lazily updates UI. (in some callbacks, we force it because Espresso cannot track the path data binding is using to delay view setting but that is a bug in espresso, not data binding).

tl;dr; The whole purpose of Architecture Components is to reduce the number of edge cases like these so we'll eventually solve them.

TonicArtos commented 7 years ago

Since you mentioned there is no easy solution, here is my solution (using Kotlin coroutines). I push values coming from LiveData into a ConflatedChannel, which only keeps the latest value. Then when the data binding has been created, I also create a consumer of the ConflatedChannel to bind the values from it. To prevent leaking on the consumer coroutine, you need to use a LifecycleObserver or one of the older life cycle callbacks.

With some extensions, this looks someting like the following.

val incomingData = ConflatedChannel<Data>()

fun onCreate(savedInstanceState: Bundle?) {
    // snip
    observeNotNull(viewModel.loadData(query)) {
        incomingData.post(UI, it)
    }
}

fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    // snip
    launch(UI) {
        incomingData.consumeEach {
            binding.data = it
        }
    }.cancelOn(this, FragmentEvent.VIEW_DESTROYED)
}
cbeyls commented 7 years ago

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.

/**
 * Fragment providing separate lifecycle owners for each created view hierarchy.
 * <p>
 * This is one possible way to solve issue https://github.com/googlesamples/android-architecture-components/issues/47
 *
 * @author Christophe Beyls
 */
public class ViewLifecycleFragment extends Fragment {

    static class ViewLifecycleOwner implements LifecycleOwner {
        private final LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);

        @Override
        public LifecycleRegistry getLifecycle() {
            return lifecycleRegistry;
        }
    }

    @Nullable
    private ViewLifecycleOwner viewLifecycleOwner;

    /**
     * @return the Lifecycle owner of the current view hierarchy,
     * or null if there is no current view hierarchy.
     */
    @Nullable
    public LifecycleOwner getViewLifeCycleOwner() {
        return viewLifecycleOwner;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewLifecycleOwner = new ViewLifecycleOwner();
        viewLifecycleOwner.getLifecycle().handleLifecycleEvent(Event.ON_CREATE);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (viewLifecycleOwner != null) {
            viewLifecycleOwner.getLifecycle().handleLifecycleEvent(Event.ON_START);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (viewLifecycleOwner != null) {
            viewLifecycleOwner.getLifecycle().handleLifecycleEvent(Event.ON_RESUME);
        }
    }

    @Override
    public void onPause() {
        if (viewLifecycleOwner != null) {
            viewLifecycleOwner.getLifecycle().handleLifecycleEvent(Event.ON_PAUSE);
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        if (viewLifecycleOwner != null) {
            viewLifecycleOwner.getLifecycle().handleLifecycleEvent(Event.ON_STOP);
        }
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        if (viewLifecycleOwner != null) {
            viewLifecycleOwner.getLifecycle().handleLifecycleEvent(Event.ON_DESTROY);
            viewLifecycleOwner = null;
        }
        super.onDestroyView();
    }
}

It can be used to register an observer in onActivityCreated() that will be properly unregistered in onDestroyView() automatically:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    viewModel.getSampleData().observe(getViewLifeCycleOwner(), new Observer<String>() {
        @Override
        public void onChanged(@Nullable String result) {
            // Update views
        }
    });
}

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?

thanhpd56 commented 7 years ago

@yigit is there any progress to fix this issue?

Zhuinden commented 6 years ago

Is this really even a bug? The lifecycle aware observers are registered until the component is destroyed. The fragment is not destroyed, only its view hierarchy is.

cbeyls commented 6 years ago

It's not a bug in itself, but the official samples show an incorrect use of LiveData in fragments and the documentation should inform about this confusion between Fragment lifecycle and View lifecycle. I wrote a full article about this last week.

Zhuinden commented 6 years ago

@cbeyls oh yeah you're right! In the BasicSample - and I messed this up in my own sample too, registering in onViewCreated (with an anonymous observer) but not unregistering in onDestroyView!

Whoops >. <

cbeyls commented 6 years ago

The video only shows a simple example involving an Activity. Things are more complex with fragment views for all the reasons mentioned above.

dustedrob commented 6 years ago

Was there ever a conclusion to this issue? just ran into this problem using fragments. What's the preferred way to move forward?

insidewhy commented 6 years ago

@dustedrob rob the article at https://medium.com/@BladeCoder/architecture-components-pitfalls-part-1-9300dd969808 lists a few possible solutions. I use the superclass + customised lifecycle one.

Hopefully one will be integrated, it's kinda funny how Google's own samples contain these errors ;)

Martindgadr commented 6 years ago

@cbeyls @yigit I have an strange behaviour on mi ViewModel Observable, I don't know why it's called more than once if I setup observers onActivityCreated Fragment event. It's called more than one between fragment transitions. Example, I have 1 Activity 3 fragments, If I move from first to third observable on first screen is called more than once. Code Example Below:

override fun onActivityCreated(savedInstanceState: Bundle?) { volumenViewModel.misRuedasRemuneracion.reObserve(this, observerRuedasRemu)
volumenViewModel.misSubordinados.reObserve(this, observerMisSubordinados) volumenViewModel.remuneracionMensualActualizada.reObserve(this, observerRemuneracionMensualActualizada) }

Base Fragment implementation: fun LiveData.reObserve(owner: LifecycleOwner, observer: Observer) { removeObserver(observer) observe(owner, observer) }

If I move these to onCreate event they are calling just once.... So why is this behaviour strange? is there any reason for that? are coming some changes on Architecture component to solve this or just it's not possible using Fragment? what happen If I just have 1 activity and some fragments and share viewmodel with multiples LiveData and need observe same live data on multiples fragments? My question, Is because I need put observables just once on onActivityCreated or onCreateView is the same, but need call on that because a reuse of sections on fragment not onCreate. Note: My architecture is Service from backend - Repository - Room Database with livedata - Viewmodel - Activity / Fragment with databinding. Thanks in advance.

insidewhy commented 6 years ago

@Martindgadr I saw similar strange behaviour when using the reobserve strategy, that's why I went for a solution involving a superclass and customised lifecycle instead, see the links pasted above.

Zhuinden commented 6 years ago

I don't think I've ever used onActivityCreated() for anything in a Fragment.

What's it for? I'd assume onAttach(Context context) can get the activity reference already?

bernaferrari commented 6 years ago

I am having the same problem with Activities, when user press back button and return, onCreate() is called (and since I'm observing on it..)... Is this normal?

Zhuinden commented 6 years ago

@bernaferrari it's normal after process death.

bernaferrari commented 6 years ago

So, is there already a right way to fix? I hate duplicated/triplicated/... log messages. BTW, wow, the hero from /androiddev here.. 😂

Edit: Forget everything I said. I was having a very dumb problem, where I was initialising Logger in onCreate, so it was initialised +1 time every time I would press back and open it..

cuichanghao commented 6 years ago

@cbeyls because recently support Fragment implementation LifecycleOwner so just need below code for remove observe.

open class ViewLifecycleFragment : Fragment() {
    override fun onDestroyView() {
        super.onDestroyView()
        (lifecycle as? LifecycleRegistry)?.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    }
}

EDIT @Kernald you're right.

open class ViewLifecycleFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        (lifecycle as? LifecycleRegistry)?.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        (lifecycle as? LifecycleRegistry)?.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
        super.onViewCreated(view, savedInstanceState)
    }
    override fun onDestroyView() {
        super.onDestroyView()
        (lifecycle as? LifecycleRegistry)?.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    }
}

don't forgot call super.onViewcreate or super.onCreateView

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model.searchArticle.observe(this, Observer { articleData ->
            setData(articleData)
        })
    }
Kernald commented 6 years ago

@cuichanghao with the solution you propose, your lifecycle doesn't really matches the fragment's one. And the creation side of your lifecycle doesn't match the destruction side anymore either (if you emit the destroy event in onDestroyView, you should emit the create event in onViewCreated).

While your solution probably works for this specific case, the idea of exposing a fragment lifecycle and a view lifecycle makes much more sense, and is probably less error prone.

yperess commented 6 years ago

Hey guys, chiming in on this "old" bug. The correct solution (which I have working in 2 production apps) is:

  1. Either extend DaggerFragment or add AndroidSupportInjection.inject(this) to onAttach as well as implement HasSupportFragmentInjector for your fragment. Note the lifecycle on: https://developer.android.com/guide/components/fragments
  2. Register all of your observers in onCreate

The key here is that onAttach and onCreate are the only methods that are guaranteed to run once per fragment instance.

Zhuinden commented 6 years ago

onCreate isn't good because if the fragment is detached and reattached (think fragment state pager) then you won't be able to update the re-created view with the latest data in ViewModel.

One day they'll release Fragments with the viewLifecycle and that'll solve issues.

For now, I think the solution is to subscribe in onViewCreated, and remove observers in onDestroyView.

cbeyls commented 6 years ago

The proper fix is to use [Fragment.getViewLifecycleOwner()](https://developer.android.com/reference/androidx/fragment/app/Fragment.html#getViewLifecycleOwner()) which is already part of AndroidX.

yperess commented 6 years ago

Thanks @cbeyls, any idea when androix will make its way into Dagger2's DaggerFragment and DaggerAppCompatActivity?

JobGetabu commented 6 years ago

any workable solution. fragments are not updating real time data :(

Zhuinden commented 6 years ago

There's a pretty good chance that that's an error on your side, though?

This Github repo doesn't have anything with "real time data" i think

hardysim commented 6 years ago

The proper fix is to use Fragment.getViewLifecycleOwner() which is already part of AndroidX.

It seems that in support lib 28.0.0-alpha01 it is not included. Can someone confirm? I cannot upgrade to androidx at the moment.

Hydrino commented 6 years ago

Yes hardysim, it is not included in 28.0.0 - alpha01.

cs-matheus-candido commented 6 years ago

FYI: alpha03 includes this, thank god

Hydrino commented 6 years ago

Oh thank God! And thank you too for informing 😁

On Mon 2 Jul, 2018, 11:11 PM Matheus Candido, notifications@github.com wrote:

FYI: alpha03 includes this, thank god

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/googlesamples/android-architecture-components/issues/47#issuecomment-401880554, or mute the thread https://github.com/notifications/unsubscribe-auth/ANNUETMDyPMtTAZULAHET-h0IDj5_E5kks5uCltNgaJpZM4Nvao1 .

nicolasjafelle commented 6 years ago

Hello! I am new using ViewModel and LiveData arch components and have the problem when using fragments and rotate the screen the observer get triggered... I tried to move the viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java) in all the fragment lifecycle methods but with no success.

My scenario is kind of really easy one:

  1. Login screen with email and password
  2. User clicks on the "login" button
  3. the viewmodel calls the login(email, password
  4. the viewModel set the value of the LiveData object
  5. Just for now simple show a Toast

At this point everything is Ok. But when I rotate the screen the Toast appears again without any user interaction.

Do I have to do something in onDestroyView() ?

JobGetabu commented 6 years ago

Have you tried to get same activity with: viewModel = ViewModelProviders.of(getActivity()).get(MainViewModel::class.java)

arekolek commented 6 years ago

Check this post for the official recommendation https://medium.com/google-developers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

It is off topic for this issue though, so don't continue this conversation here.

Here's the issue you were looking for https://github.com/googlesamples/android-architecture-components/issues/63

victsomie commented 6 years ago

Could somebody be having this challenge still?

I encountered the same while using ViewModel inside fragment, which were working on my Activities. I solved by making my Fragment inherit from DaggerFragment. (MyFragment extends DaggerFragment)

adam-hurwitz commented 6 years ago

Hi @yigit, @cbeyls, and @victsomie, I am working through a similar issue outlined on Stackoverflow.

I have multiple LiveData Observers that are being triggered in a Fragment after navigating to a new Fragment, popping the new Fragment, and returning to the original Fragment.

Details: The architecture consists of MainActivity that hosts a HomeFragment as the start destination in the MainActivity's navigation graph. Within HomeFragment is a programmatically inflated PriceGraphFragment. The HomeFragment is using the navigation component to launch a new child Fragment ProfileFragment. On back press the ProfileFragment is popped and the app returns to the HomeFragment hosting the PriceGraphFragment. The PriceGraphFragment is where the Observer is being called multiple times.

You can see the StackOverflow more detailed implementation.

Attempted Solutions

  1. Creating the Fragment's ViewModel in the onCreate() method. priceViewModel = ViewModelProviders.of(this).get(PriceDataViewModel::class.java)
  2. Moving methods that create the Observers to the Fragment's onCreate() method.
  3. Using viewLifecycleOwner instead of this for the LifecycleOwner in the method observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer).
TonicArtos commented 6 years ago

My solution is to create the observers in the fragments onCreate method. This way they'll only be created once. Accessing views within the observers is fine because they are lifecycle controlled so they are only called after onViewCreated.

On Fri, 17 Aug 2018, 10:53 AdamHurwitz, notifications@github.com wrote:

Hi @yigit https://github.com/yigit, @cbeyls https://github.com/cbeyls, and @victsomie https://github.com/victsomie, I am working through a similar issue outlined on Stackoverflow https://stackoverflow.com/questions/51892478/multiple-livedata-observers-after-popping-fragment .

I have multiple LiveData Observers that are being triggered in a Fragment after navigating to a new Fragment, popping the new Fragment, and returning to the original Fragment.

Details: The architecture consists of MainActivity that hosts a HomeFragment as the start destination in the MainActivity's navigation graph. Within HomeFragment is a programmatically inflated PriceGraphFragment. The HomeFragment is using the navigation component to launch a new child Fragment ProfileFragment. On back press the ProfileFragment is popped and the app returns to the HomeFragment hosting the PriceGraphFragment. The PriceGraphFragment is where the Observer is being called multiple times.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/googlesamples/android-architecture-components/issues/47#issuecomment-413816717, or mute the thread https://github.com/notifications/unsubscribe-auth/AASEzoVGos54gMf0PHVris7YrHSnWFroks5uRpJ-gaJpZM4Nvao1 .

cbeyls commented 6 years ago

You can do what @TonicArtos suggests but don't forget that if you do that, you'll have to update the views manually by fetching the latest result from the LiveData in onActivityCreated() when the fragment is re-attached. That's because the observer doesn't change so the latest result won't be pushed automatically to the new view hierarchy, until a new result arrives.

adam-hurwitz commented 6 years ago

Thanks for the feedback @TonicArtos and @cbeyls!

@TonicArtos - I've created all Observers in onCreate() method and am still seeing the Observers called 2 additional times. In my log below this is represented by the observeGraphData() statement I'm printing out when the Observer is fired.

screen shot 2018-08-17 at 10 50 47 am

@cbeyls - Thank you for the heads up. As I'm still seeing multiple Observers with @TonicArtos's strategy I haven't gotten to this stage of implementation.

Perhaps the issue is related to creating the nested ChildFragment (PriceGraphFragment) in the ParentFragment's (HomeFragment) onViewCreated()?

ParentFragment

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        user = viewModel.getCurrentUser()
        if (savedInstanceState == null) {
            fragmentManager
                    ?.beginTransaction()
                    ?.add(binding.priceDataContainer.id, PriceGraphFragment.newInstance())
                    ?.commit()
        }
TonicArtos commented 6 years ago

Every time you write out the log line for observerGraphData, add the object hashcode. That will tell you if it is a duplicate observer, or if something else is sending data to the liveData multiple times.

On Fri, 17 Aug 2018, 18:53 AdamHurwitz, notifications@github.com wrote:

Thanks for the feedback @TonicArtos https://github.com/TonicArtos and @cbeyls https://github.com/cbeyls!

@TonicArtos https://github.com/TonicArtos - I've created all Observers in onCreate() method and am still seeing the Observers called 2 additional times. [image: screen shot 2018-08-17 at 10 50 47 am] https://user-images.githubusercontent.com/3938076/44281089-7a993100-a20b-11e8-9d34-3fb2a5a4fff7.png

@cbeyls https://github.com/cbeyls - Thank you for the heads up. As I'm still seeing multiple Observers with @TonicArtos https://github.com/TonicArtos's strategy I haven't gotten to this stage of implementation.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/googlesamples/android-architecture-components/issues/47#issuecomment-413941664, or mute the thread https://github.com/notifications/unsubscribe-auth/AASEzhrLnjXBr8zj8cy4YT6zAiPCyBWdks5uRwMXgaJpZM4Nvao1 .

adam-hurwitz commented 6 years ago

@TonicArtos, great idea.

I'm logging the hashcode of the HashMap being emitted by the Observer and it is showing 2 unique hashcodes when I go to the child Fragment, pop the child Fragment, and return to the original Fragment.

This is opposed to the one hashcode seen from the HashMap when I rotate the screen without launching the child Fragment.

TonicArtos commented 6 years ago

I would suggest then, that if your observers are added only in Fragment::onCreate, then perhaps you have multiple instances of the fragment, either sequentially or simultaneously.

It is difficult to surmise further without code samples in a gist.

On Tue, 21 Aug 2018, 20:33 AdamHurwitz, notifications@github.com wrote:

@TonicArtos https://github.com/TonicArtos, great idea.

I'm logging the hashcode of the HashMap being emitted by the Observer and it is showing 2 unique hashcodes.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/googlesamples/android-architecture-components/issues/47#issuecomment-414794771, or mute the thread https://github.com/notifications/unsubscribe-auth/AASEzqqg-2Cc6sD2fQQAScWhxyWwGqNGks5uTGCFgaJpZM4Nvao1 .

adam-hurwitz commented 6 years ago

First off, thank you to everyone who posted here. It was a combination of your advice and pointers that helped me solve this bug over the past 5 days as there were multiple issues involved. I've posted the answer below in the corresponding Stackoverflow. Please provide feedback there if my solution provides value to you.

Issues Resolved

  1. Creating nested Fragments properly in parent Fragment (HomeFragment).

Before:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

        if (savedInstanceState == null) {
        fragmentManager
                ?.beginTransaction()
                ?.add(binding.priceDataContainer.id, PriceGraphFragment.newInstance())
                ?.commit()
        fragmentManager
                ?.beginTransaction()
                ?.add(binding.contentFeedContainer.id, ContentFeedFragment.newInstance())
                ?.commit()
    }
...
}

After:

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    if (savedInstanceState == null
            && childFragmentManager.findFragmentByTag(PRICEGRAPH_FRAGMENT_TAG) == null
            && childFragmentManager.findFragmentByTag(CONTENTFEED_FRAGMENT_TAG) == null) {
        childFragmentManager.beginTransaction()
                .replace(priceDataContainer.id, PriceGraphFragment.newInstance(),
                        PRICEGRAPH_FRAGMENT_TAG)
                .commit()
        childFragmentManager.beginTransaction()
                .replace(contentFeedContainer.id, ContentFeedFragment.newInstance(),
                        CONTENTFEED_FRAGMENT_TAG)
                .commit()
    }
...
}
  1. Creating ViewModels in onCreate() as opposed to onCreateView() for both the parent and child Fragments.

  2. Initializing request for data (Firebase Firestore query) data of child Fragment (PriceFragment) in onCreate() rather than onViewCreated() but still doing so only when saveInstanceState is null.

Non Factors

A couple items were suggested but turned out to not have an impact in solving this bug.

  1. Creating Observers in onActivityCreated(). I'm keeping mine in onViewCreated() of the child Fragment (PriceFragment).

  2. Using viewLifecycleOwner in the Observer creation. I was using the child Fragment (PriceFragment)'s this before. Even though viewLifecycleOwner does not impact this bug it seems to be best practice overall so I'm keeping this new implementation.

Draketheb4dass commented 5 years ago

btw, @@brenoptsouza about 1, great news is that it won't be a problem because LiveData callbacks are not called outside onStart-onStop so view will be ready for sure.

What if new data has been added have been fetch from the server, will the observer still be notified and sync?

channae commented 5 years ago

This seems really messed up. I tried removing the attached Observer of the LiveData during onCreateView of the fragment. I called remove method before start observing again.

Still I get duplicates. Seems like getUserList to get LiveData object for observer removal adds more data.

After doing this change my RecyclerView doubles up values in the first fragment load itself.

eg: userViewModel.getUserList().removeObserver(....)

Zhuinden commented 5 years ago

You're supposed to do liveData.observe(viewLifecycleOwner) { obj -> ... }

KaranMavadhiya commented 5 years ago

I am facing same issue in Fragment ...

I tried removing the attached Observer of the LiveData after getFragmentManager().popBackStack(); in Observer.

// Observer for ForgotPassword with Email API call forgotPasswordViewModel.getForgotPasswordLiveData().observe(this,this::handleForgotPasswordResponse);

`private void handleForgotPasswordResponse(ResponseModel responseModel) { AlertDialogUtil.showAlertDialog(getContext(), getString(R.string.app_name), responseModel.getMessage(), getString(R.string.str_ok), false, (dialog, which) -> {

        assert getFragmentManager() != null;
        getFragmentManager().popBackStack();

        if (forgotPasswordViewModel != null && forgotPasswordViewModel.getForgotPasswordLiveData().hasObservers())
            forgotPasswordViewModel.getForgotPasswordLiveData().removeObserver(this::handleForgotPasswordResponse);

    });
}`

When i call Fragment again Observer will call without any event call

Zhuinden commented 5 years ago

You shouldn't need to manually remove observers like that.

So the fact that you're doing that probably means that your code logic contains some kind of error, and should be done differently.