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

Changing fragments without losing fragment view model data, not using ShowViewModel(?) #267

Closed Cybrosys closed 8 years ago

Cybrosys commented 8 years ago

I have a MvxCachingFragmentCompatActivity. I have four fragments. Some of these fragments' view models require parameters passed in, in order for them to be able to initialize/work. The params gets passed in from another activity to ShowViewModel() (they're never passed directly to the hosting activity).

I'm using the Bottom Nav Bar (Tabs from the bottom), which means that I have to change the current visible fragment, from the activity. If I do it like your sample, exposing ShowViewModel, then the view models don't get initialized with the params needed from the previous activity (because we don't know about them).

At the moment it's only the first fragment being shown/triggered externally that has data that needs to be saved.

So how can I toggle between fragments from the activity without recreating them and their view models? Isn't that what the MvxCachingFragmentCompatActivity is supposed to solve?

Maybe I'm just missing something completely/bad configuration. I thought that calling ShowViewModel would check if the fragment and viewmodel was cached, and if that was the case then restore it (the VM have Init, ReloadState, Start and SaveState methods)?

Update I added the following to my fragment base class: RetainInstance = true AddToBackStack = true

In the activity method/callback for when a tab has been selected. I go over the fragments in GetCurrentCacheableFragments() and see if the desired ViewModel is already loaded.

If so, I directly access the SupportFragmentManager and do a Replace. If not, I do a ShowViewModel.

Is there a better way of handling this?

Update 2 The main issue is that the hosting activity's view model needs to have state set in order to properly call ShowViewModel for the other fragment view models. Since the starting activity calls ShowViewModel on the primary fragments view model, the hosting activity just gets created as a side effect.

So i'll either pass data from the fragment to the hosting activity's vm, or show the hosting activity view model with the data needed for the fragments, and then it's up to the hosting activity (or its vm) to show the primary fragment view model.