Thursday, November 07, 2013

N=42 - Is my ViewModel visible? Can I kill it?

Today's N+1 is all about whether or not your ViewModel is Visible - and about how to kill it when it gets removed from the screen.


This is a fairly FAQ topic - see questions like http://stackoverflow.com/questions/15961664/viewmodel-lifecycle-when-does-it-get-disposed and http://stackoverflow.com/questions/19816819/how-are-views-and-viewmodels-freed-up-in-mvvmcross


MvvmCross doesn't provide any built-in event notification - but it is easy to add it for your app.


In this video, I show how to add and invoke interfaces like these to some view models which are shown by a standard MvvmCross presenter:




If you have custom presentation, then you'll need to adapt this technique to suit your needs - but, since it is your custom presentation, then you should hopefully be in the best place to do this.


The source for today's video is in https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/tree/master/N-42-Lifecycles


The video itself is:




The audio skips in the first few seconds - making me sound even odder than normal ;)


For a full N+1 index, please see Aboo's fabulous work on http://mvvmcross.wordpress.com

1 comment:

  1. 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.

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


    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);
    }

    ReplyDelete