Warm tip: This article is reproduced from stackoverflow.com, please click
xamarin.forms mvvm prism

How to Dispose a ViewModel after Popping a page with Xamarin.Forms?

发布于 2020-03-27 15:46:42

What I would like to do is unsubscribe from events at the moment the ViewModel is no longer needed. I tried implementing IDisposable but nobody calls Dispose(), not Xamarin.Forms nor Prism.Forms.

We have an app created with Xamarin.Forms. We use Prism.Forms to do MVVM. When navigating to a new page (push on stack) Prism.Forms wires the ViewModel to the Page. When navigating back (pop from stack) the ViewModel gets GarbageCollected after a while.

The problem is however that at a point in time we have a couple of the same type of ViewModels with subscriptions to events that are not bound to a View. When the events fire all these ViewModels start doing their thing. So I am looking for a way to unsubscribe at the moment the subscription is no longer needed.

Does anyone have a solution?

Questioner
Jacco Dieleman
Viewed
595
Rohit Vipin Mathews 2016-08-25 17:44

You can make sure the Dispose() is called in the OnDisappearing() event of the View, if you want to ensure that ViewModel is not present anymore in the memory than the view.

It is better if you care only about subscribe and unsubscribe of events, then to do it in the OnAppearing() and OnDisappearing(). In that case you will be sure of no event handlers been present on the viewmodel once view is not visible.