开发者

Event Aggregation...What exactly is going on?

开发者 https://www.devze.com 2022-12-11 19:00 出处:网络
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 i

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 Presentati开发者_开发知识库on 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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消