Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubscribe EventAggregator events in ViewModels

Tags:

mvvm

wpf

prism

I start using WPF with PRISM and MVVM. One problem I am facing is that I can’t find a good place / best practice to unsubscribe EventAggregator events formerly subscribed in the ViewModel. The following solution - calling Unsubscribe in the destructor – is much too late. It is just running with the next garbage collection.

public class ViewModel : ViewModelBase
{
    public ViewModel()
    {
        var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
        eventAggregator.GetEvent<SeriesSelectionChangedEvent>().Subscribe(OnSeriesSelectionChanged);
    }

    ~ViewModel()
    {
        var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
        eventAggregator.GetEvent<SeriesSelectionChangedEvent>().Unsubscribe(OnSeriesSelectionChanged);
    }

    void OnSeriesSelectionChanged(SeriesSelectionChangedEventArgs e)
    {
    }
}
like image 751
Dirk Brockhaus Avatar asked Apr 28 '11 15:04

Dirk Brockhaus


People also ask

What is EventAggregator in Prism?

In the Prism Library, the EventAggregator allows subscribers or publishers to locate a specific EventBase . The event aggregator also allows for multiple publishers and multiple subscribers, as shown in the following illustration.

What is an event aggregator?

An Event Aggregator acts as a single source of events for many objects. It registers for all the events of the many objects allowing clients to register with just the aggregator.

What is event aggregator WPF?

For those unfamiliar, an Event Aggregator is a service that provides the ability to publish an object from one entity to another in a loosely based fashion. Event Aggregator is actually a pattern and it's implementation can vary from framework to framework. For Caliburn.


1 Answers

It's up to you! If your application can notify ViewModel when it is no longer needed, so you should unsubscribe there.

For example, in our project we have IViewDisposeService. If view (or its model) needs deterministic finalization, it registers itself in IViewDisposeService when showing. Then the Core use the same service to notify registered views when they've been removed from regions.

Another way is to use commands. Your model expose command which must be invoked by a view when it is closing. ViewModel may use command handler to unsubscribe.

By the way, if you worry that EventAggregator will hold your ViewModel, it's not a problem, because Prism's EventAggregator use weak references.

like image 182
Marat Khasanov Avatar answered Sep 21 '22 22:09

Marat Khasanov