-1

I have been reading this post from Stuart Logde on how to kill the ViewModel when the view disappears.

http://slodge.blogspot.dk/2013/11/n42-is-my-viewmodel-visible-can-i-kill.html

I have a complex ViewPresenter where sometimes I present a ViewController with a UINavigationController modally and then allow navigation within this. Once navigated into another ViewController and pressing Done, I dismiss the entire UINavigationController and all of its ViewControllers. The ViewWillDisappear is not called on other views than the topmost, since they are already disappeared, hence I need another mechanism.

Would it be wrong to follow an approach like the following in MvxViewController on iOS?

private bool viewModelKilled;

protected override void Dispose (bool disposing)
{
    if (!viewModelKilled)
    {
        var killableViewModel = ViewModel as IKillableViewModel;
        if (killableViewModel != null)
        {
            killableViewModel.KillMe();
        }

        viewModelKilled = true;
    }

    base.Dispose (disposing);
}

This is more like the normal 'dealloc' approach in iOS where one often unregister from observing other objects.

dynamokaj
  • 471
  • 7
  • 19
  • If you use the ViewPresenter to present the views, why not use it to Dispose them as well? – Mark Verkiel Apr 20 '16 at 12:02
  • I had the impression that in Xamarin you do not call Dispose manually on your Views, you let the GarbageCollector do this. However the Dispose method in the View is in fact called, my question is more about if it is okay to call the ViewModel from the Dispose method and tell the ViewModel to unregister from EventHandler etc. in order to also let the ViewModel being Disposed. – dynamokaj Apr 20 '16 at 12:04

1 Answers1

0

In your custom presenter, override

public override void Show(MvxViewModelRequest request)

You might discard a full navigation controller by calling a ShowViewModel on an ancestor which is already in the stack. So this Show method is always called, and will pop the existing viewcontroller hierarchy. You can also use a 'hint' in ShowViewModel which is passed in request.

It does know the existing viewcontroller hierarchy, before and after the pop. So it does know each discarded vc. You have to call Dispose on each popped vc (Xamarin may do it for you ... after a few minutes. Except if you have hard references to your viewmodel or to another service. Its too long and my experience shows it will fill your memory).

Calling Dispose on the viewcontroller is sufficient to trigger an automatic Dispose on the ViewModel. If you don't want to wait you can also call Dispose on the viewmodel, knowing the viewcontroller it's easy to get the Viewmodel (property: ViewModel !).

Hope it helps.

Softlion
  • 12,281
  • 11
  • 58
  • 88