Event Driven Programming in C# — Observer Pattern
In my previous post — Event Driven Programming in C#, I went through the basics of using the publisher-subscriber method to implement an event driven architecture in an ASP.Net Core application.
In this post, we take a look at the Observer Pattern — another way of implementing event-driven programming in C#.
Observer vs Publisher-Subscriber Pattern
At first glance, the Observer pattern appears almost identical to the Pub-Sub pattern.
An Observable (Publisher) emits events.
An Observer (Subscriber) subscribes to the Observable, and performs actions as event notifications are sent out.
The key difference here is in how event notifications are communicated to observers(subscribers).
In the Pub-Sub pattern, event notification occurs through the use of an event handler — an abstraction layer which decouples publisher from subscriber. The publisher does not need to know about subscribers.
In the Observer pattern, Observables (Publishers) must keep track of Observers (Subscribers). The Observable sends events to each Observer.
Personally, I would choose Pub-Sub over Observer pattern because the architecture is much more loosely coupled…