Prism UWP for beginners: events

In this post we explore another major component of Prism: the EventAggregator.

The Prism library provides an event mechanism to communicate between loosely coupled components in the application. Using .NET Framework events is the most straightforward approach for communication between components if loose coupling is not a requirement. Events in the .NET Framework implement the Publish-Subscribe pattern, but to subscribe to an object, you need a direct reference to that object, which, in composite applications, typically resides in another module. This is a tightly coupled design.

The EventAggregator provides a mechanism to matain the application loosely-coupled. It provides a multicast publish/subscribe funcionality (there can me multiple publishers of the same event with multiple subscribers).

image

We can obtain a reference to the EventAggregator using the container, for example we can write this code in the OnInitializeAsyunc method of the App class that is our bootstrapper.

protected override Task OnInitializeAsync(IActivatedEventArgs args)
         {
Container.RegisterInstance<IEventAggregator>(new EventAggregator());
return base.OnInitializeAsync(args);
         }

Events

Before we start publishing and subscribing to events we need to declare them. Events are simple classes that inherit from PubSubEvent<T> in the Prism.Event namespace. T is the type of the payload of our message. We declare our simple event like this:


class SimpleEvent : PubSubEvent<string>
     {

    }

In this case we defined an event which payload is a string.

Publisher

Now let’s make an example of a viewmodel that publishes an event of that type.


class PublisherViewModel {

	public DelegateCommand SendMessage { get; private set; }

        private readonly IEventAggregator _eventAggregator;

	public PublisherViewModel(IEventAggregator eventAggregator)
        {
            if (eventAggregator == null)
            {
                throw new ArgumentNullException(nameof(eventAggregator));
            }

            _eventAggregator = eventAggregator;

            SendMessage = new DelegateCommand(() =>
            {
                _eventAggregator.GetEvent<SimpleEvent>().Publish(DateTime.Now.ToString());
            });
        }
}

In the constrctor we specified a parameter to hold a reference to an instance of IEventAggregator. The container will do the heavylifting and inject the parameter every time we need an instance of PublisherViewModel. We defined a DelegateCommand that publishes a message using the EventAggregator: that message will have the currente date and time in string format.

Subscriber

Now we can define a subscriver view-model that listens to this type of events.

 

class SubscriberViewModel
{
       private readonly IEventAggregator _eventAggregator;	

	public SubscriberViewModel(IEventAggregator eventAggregator)
	{
		if (eventAggregator == null)
		{
			throw new ArgumentNullException(nameof(eventAggregator));
		}
		_eventAggregator = eventAggregator;

		_eventAggregator.GetEvent<SimpleEvent>().Subscribe((dateDesc) =>
{
//Do something with datedesc.
});
	}
} 

With the

_eventAggregator.GetEvent<SimpleEvent>().Subscribe(...)

line of code we set our SubscriberViewModel class to listen to events of type SimpleEvent and we can specify what we would like to do when the class is notified.

And that’s it! Managing messages between components is very easy thanks to Prism.

TL;DR

In this post we learned how components can communicate in a Prism app in a decoupled fashion. The EventAggregator is the main actor of this funcionality and it acts as a post office to deliver messages from publishers to subscribers.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s