views:

168

answers:

1

Hi,

I have often times wondered about it but now that I have encountered a piece of logic that incorporates it, I thought I should go ahead and get some help on deciphering the fundamentals. The problem is as follows, I am looking at a WPF application that is utilizing the Composite Application Library. Within the source of the application I came across the following line of code in the Presentation of a view. For the sake of convinience I will call it Presentation A:

private void OnSomethingChanged(SomeArgumentType arguement)
{
   UnityImplementation.EventAggregator.GetEvent<EventA>().Publish(null);
}

When I saw the method Publish in the above given method, my gut told me there must be a Subscribe somewhere and in another class, I will call it Presentation B there was the following:

UnityImplementation.EventAggregator.GetEvent(Of EventA).Subscribe(AddressOf OnSomeEventA)

There was a private function in the same class called OnSomeEventA that had some logic in it.

My question here is that how is everything wired over here? What exactly is achieved by the 'Publish' 'Subscribe' here? When 'something' changes, how does the compiler know it has to follow the logic in OnSomethingChanged that will 'Publish' an event that is 'Subscribed' by another class where the logic of the event handler has been described? It will be great to understand the underlying wiring of this process.

Thanks

+1  A: 

The first time GetEvent<T> is called for each event (identified by the type parameter T) the EventAggregator creates an empty list of methods to call when that event is published. Typically, this will happen immediately before the first call to Publish or Subscribe (as in your examples).

Then:

  • Whenever Subscribe is called a method is added to the list.
  • Whenever Publish is called it walks through the list and makes those calls.

So, the call to Publish() in Presentation A results in all of the methods that have been registered by calling Subscribe being called, which in your example would include Presentation B's OnSomeEventA method.

Try setting a breakpoint in the OnSomeEventA method and take a look at the stack, and don't forget the source is available, too!

GraemeF
Thanks GraemeF. I understand that the Event Aggregator is maintaining a list of methods to call when the Publish is invoked. But I am still a little confused by the Subscription part. Is the subscription done during runtime or during the initial compilation process?
sc_ray
Everything happens at runtime. I added a bit more detail to my answer - hope that helps!
GraemeF
Makes perfect sense. Thanks a lot!
sc_ray