Reputation: 1573
According to the information I can find, the MvvmCross Viewmodel life cycle is
Construction - using IoC for Dependency Injection
Init() - initialisation of navigation parameters
ReloadState() - rehydration after tombstoning
Start() - called when initialisation and rehydration are complete
I have implemented mine as follows:
public async Task Init(Guid ID)
{
await MPS_Mobile_Driver.Droid.DataModel.ShipmentDataSource.GetShipmentInventory(ID);
ShipmentInventory = ShipmentDataSource.CurrInventory;
ShipmentLots = await MPS_Mobile_Driver.Droid.DataModel.ShipmentDataSource.GetShipmentLotList((int)ShipmentInventory.idno, (short)ShipmentInventory.idsub);
Inv_DamageList = await ListDataSource.GetInv_Damage();
}
protected override void SaveStateToBundle(IMvxBundle bundle)
{
base.SaveStateToBundle(bundle);
bundle.Data["ShipmentInventory"] = StringSerializer.SerializeObject(ShipmentInventory);
bundle.Data["ShipmentLots"] = StringSerializer.SerializeObject(ShipmentLots);
bundle.Data["Inv_DamageList"] = StringSerializer.SerializeObject(Inv_DamageList);
}
protected override void ReloadFromBundle(IMvxBundle state)
{
base.ReloadFromBundle(state);
ShipmentInventory = StringSerializer.DeserializeObject<ShipmentInventory>(state.Data["ShipmentInventory"]);
ShipmentLots = StringSerializer.DeserializeObject<ShipmentLotList>(state.Data["ShipmentLots"]);
Inv_DamageList = StringSerializer.DeserializeObject<Inv_DamageList>(state.Data["Inv_DamageList"]);
state.Data.Clear();
}
First off, I can't seem to get the emulator to actually destroy the Activity when I hit the Home key even though I have that option checked. The activity seems to hang around in the background anyway.
That being said, when I do hit the home key, It calls SaveStateToBundle. What it never seems to do is to call ReloadFromBundle. This makes it hard to test What is actually going on. My fear is that according to the life cycle, if the app does recover from a tombstone, it will call Init before it calls ReloadFromBundle. Since Init is the preferred way to pass a parameter to a ViewModel, it only makes sense to it should use the parameter to initialize the data. If after this happens, it calls ReloadFromBundle, It would overwrite the data initialized in Init. This is fine but very inefficient. Is there a way to know in Init if the ViewModel is being created due to a new navigation or if it is recovering from a tombstone?
Thanks for any help with this.
Jim
Upvotes: 2
Views: 1181
Reputation: 3401
I have the same issue with ReloadFromBundle(IMvxBundle state)
, it is never called. Only the "SaveState" pattern seems to work.
I can answer to your second question though:
You shouldn't use Init
to load your data. You should only use it to pass ids of data to be retrieved. The "loading" phase should happen in the Start
method.
Upvotes: 3