Search code examples
androidxamarinxamarin.androidmvvmcross

MvvmCross fragment backstack not restored properly


Hi Xamarin/MvvmCross devs,

I am having a problem with the MvxCachingFragmentCompatActivity, or I think it's a problem. I don't know if it's expected behaviour or not.

In my app I use fragments inside a container view. I'm having a problem with the FragmentBackStack when the activity is being restored after destruction. If I go three levels in from my initial fragment, go into the background and come back to the foreground only the last two views are restored. Note this is with "Don't keep activities" switched on in developer options.

Is there any specific setup/indication I have to give to MvvmCross to indicate too them that I want them to handle my viewmodel save/restore functionality. I don't see any in the samples I went through.

I use to use a manual approach with older versions of MvvmCross where I stored a reference to all my viewmodels in the ContainerViewModel and then just read that up when it's restored. But this doesn't work particularly well when you can have multiple of the same view on the backstack.

I have nothing special in the app, it's base usage of MvxFragment for all the views. I do have a custom presenter, but I only override ShowFragment so I can show popup views instead of replacing. None of the views not being restored uses this functionality, so it's not interfering with anything.

Any help would be grately appreciated. Dane

Update 1

Keep in mind that views in this case are MvxFragments.

while researching this I found some weird backstack behaviour associated with the MvxCachingFragmentActivity. While doing the restore functionality I got fragment tag not found in cache errors, so I added this

FragmentCacheConfiguration.RegisterFragmentToCache<View, ViewModel>(typeof(ViewModel).FullName);

When I add this for my view that's displayed second (after the first view), the first view is never added too the backstack. Causing a weird back navigation bug where back would close on the second view even if AddToBackstack is set too true for the first view we navigated from.

When I remove that line the navigation works completely fine. I have no idea why that is.


Solution

  • There were two reasons the MvxCachingFragment was not restoring the fragment backstack properly and had the weird navigation issues after coming back from the backgroun.

    1. I did not set RetainInstance = true; for the fragments. Since I had many I created a base fragment using MvxFragment and set Retain Instance true in the constructor.

    2. I did not have MvvmCross-Json-Plugin installed. Which is used for deserializing the stored viewmodel information from the Bundle.