Nilzor / mvp-to-mvvm-transition

Example project of building a MVVM-based Android app using Data Binding
http://tech.vg.no/2015/07/17/android-databinding-goodbye-presenter-hello-viewmodel/
150 stars 36 forks source link

ViewModels should be cleaned up when the view is closed. #2

Closed HNeukermans closed 9 years ago

HNeukermans commented 9 years ago

Dear,

I am a developer myself, with many years of experience in Silverlight (WPF), MVVM.

You should be aware that in mvvm coded environments, viewmodels life apart from the views. The views are created and managed by the native platform. The viewmodels, on the other hand need to be managed by the developer himself. If your viewmodels are not properly disposed, it could create memory leak problems. You can solve this by forwarding the destroy event up to the viewmodel level. that would allow the viewmodel to for example unsubscribe itself, and do other clean up.

Nilzor commented 9 years ago

The viewmodels, on the other hand need to be managed by the developer himself. If your viewmodels are not properly disposed, it could create memory leak problems.

It could, but it won't in this example. The View and the ViewModel hold circular references to each other. This is not a problem for the garbage collector. edit: Just to clarify, once the system dispose of the View, nothing is left to reference either the View or the ViewModel (they only reference each other), so they are garbage collected. If you start referencing the ViewModel from other places in your code, you should be careful though.

This is not a framework - merely an example on how to implement ViewModels and how that reduces the need for a Presenter. If you're developing a framework, you might consider a IUILifeCycle interface as you describe in issue #1, but that has some drawbacks as well which I'd consider thoroughly before doing (I'm thinking of the need for a base class for Fragment, Activity etc, and the negative impacts of having to extend classes instead of building an architecture based on composition).

In any case there already exists frameworks that help you with this, like Mosby