Search code examples
windows-phone-8mvvmcross

How are views and viewmodels freed up in MvvmCross?


I am trying to understand how MvvmCross manages memory on Windows Phone.

I try to mark my view and viewmodel as IDisposable, but the Dispose method is never called.

What I need to do is to make sure that I can free up some resources while my app is running location tracking in the background.

Christian


Solution

  • In MvvmCross:

    • each View references its ViewModel
    • the platform-specifiic operating system decides when to dereference the View - when this occurs it normally calls a method on the View (but this does depend on whether the view is a page, a tab, a flyout, a dialog, a custom control, etc)
    • the .Net or Mono Garbage Collector then decides when to collect both the Views and ViewModels from memory

    If you want to do more "active" monitoring of when the View is visible for "page-level" Views, then you need to monitor "page-level" View-specific events like:

    • ViewDidAppear \ ViewDidDisappear \ removeFromParentViewController (iOS)
    • OnResume \ OnPause`OnFinish` (Droid)
    • OnNavigatedTo`OnNavigatedFrom` (Windows)

    A generalised form of these events can then be easily called on a custom interface on your ViewModel (this can be IDisposable if you want - this is your application code).

    Update: I have blogged about this and published a sample - see http://slodge.blogspot.co.uk/2013/11/n42-is-my-viewmodel-visible-can-i-kill.html

    There's a bit more info on this in: