MvvmCross / MvvmCross-AndroidSupport

Android support library packages for MvvmCross: The .NET MVVM framework for cross-platform solutions.
http://mvvmcross.com
15 stars 0 forks source link

Rotating with Fragments fails with saved states #266

Closed Skycoder42 closed 8 years ago

Skycoder42 commented 8 years ago

Rotating with Fragments that have a saved state will fail. Consider the following: I have a simple MvxCachingFragmentCompatActivity With a single MvxFragment inside. The Fragments viewmodel will save and restore it's state to an MvxBundle.

If I now rotate, the following happens:

Now as you can see, there are now 2 viewmodels at the same time, with only one beeing used. The real problem however occurs, if you rotate a second time, with a different state:

As you can see, after the second rotation the old state is reused.

There are basically two ways to fix this. I assume the error here is the wrong order: Debugging showed that the fragments get created before the state is restored. This is the origin of this error. Thus, in this pull-request, all I did was to move the code from OnPostCreate to OnCreate, because this one gets called before fragments are created.

However, you can also change the behavior of the MvxMultipleViewModelCache to overwrite existing viewmodels in the cache. This would save the problem too.

Note: If you need a working example, just leave a comment. But there is no complicated setup needed. Just a Fragment with a viewmodel and a changing saved state.

martijn00 commented 8 years ago

I think there was a reason this moved to OnPostCreated, but i can't remember what it was. Can you see in the history if there where any comments about it in the commit?

Skycoder42 commented 8 years ago

As far as the history goes, this was always in OnPostCreate

martijn00 commented 8 years ago

Lets try and merge this. I see you still call OnPostCreate from the OnCreate method, so that needs to be fixed.