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

随声附和 提交于 2020-06-26 02:46:54

问题


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?


回答1:


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.




回答2:


Implement IDestructible or INavigationAware

(or both as in BaseViewModelsample from Prism).


Depending on your object lifecycle :

  • Implement your disposal code in the Destroy method of IDestructible interface.
  • Implement your disappearing/appearing code in the OnNavigatedFrom/OnNavigatedTo methods on INavigationAware interface.

Bonus: IDestructible can be implemented also by the View (and it will called accordingly by Prism when the view is destroyed).

Note:
While the solution above using OnAppearing/OnDisappearing works, it induces that ViewModel will depends on a call from View for managing its lifecycle (not clean). Moreover these methods don't exist on ContentView.



来源:https://stackoverflow.com/questions/39127016/how-to-dispose-a-viewmodel-after-popping-a-page-with-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!