Search for a command to run...

One object changes state. Several others need to know about it. That situation is everywhere in software: a value changes and a display must refresh, a file arrives and a pipeline must start, an order is placed and half the system must react. The obvious way to handle it is to wire the changing object to everything that cares - call each one directly. That works exactly once. The second dependent makes the wiring visible. The fifth makes it the main thing you maintain.
The Observer pattern answers with a reversal: the changing object announces the change and knows nothing about who listens. The Gang of Four book defines it as a one-to-many dependency - when one object changes state, all its dependents are notified automatically. Two roles, and only two. The subject keeps a list of subscribers and tells them when something happens. The observers subscribe, get notified, and unsubscribe when they are done. The subject never names a subscriber; it only knows the interface. All the decoupling in the pattern lives in that one fact.
There are two flavours of notification, and the distinction shapes everything that follows. Push: the subject sends the data with the notification - here is what changed. Pull: the subject sends 'something changed' and each observer asks for what it needs. Push is simpler for the observer; pull keeps the subject from deciding what anyone needs. Most .NET code pushes, and this post pushes too - but keep the distinction in mind, because the pattern's twin works the other way around.
Make it concrete. An order is placed. Three things need to happen: the customer gets a confirmation email, the stock count drops, and the sale is recorded for analytics. The straightforward way is three method calls inside the checkout handler - send the email, update the stock, record the sale. It works. Then the business asks for a fourth thing: a Slack message to the warehouse channel. You edit the handler again. Then a fifth. The handler becomes a list of everyone who cares about an order, and every new reaction means opening up code that was already working. Apply the pattern instead: the handler announces one fact, whoever cares subscribes, and the handler never changes again.
Before the framework version, the shape by hand. A subject holds a list of observers. Subscribe adds one and hands back a ticket for leaving. Notify loops the list. That is all the machinery there is:
Two details worth noticing. First, Subscribe returns IDisposable, and disposing it is the unsubscribe. Subscription lifetime is a resource lifetime - the same IDisposable idea that closes files and database connections, now applied to 'stop telling me'. Second, the publisher holds a list of an interface, not of email senders and stock services. It has no idea who is listening, and that ignorance is the feature.
The intro drew the push/pull distinction in the abstract. Here it is in code, on the same order example. Both versions notify the same way. They differ in one decision: who carries the data.
Push is what the hand-built subject above already does: Publish hands the order to every observer, and the observer works with what it was given - it never calls back into the subject:
Pull turns it around: the subject sends only the fact that something changed. The observer then asks the subject for whatever it needs - which means the observer holds a reference to the subject and knows what to ask:
The trade-off is about who knows what. Push keeps the observer ignorant of the subject - it gets data and acts - but every observer receives the same payload whether it needs all of it or not, and changing the payload touches every observer. Pull keeps the subject ignorant of what observers need - it just says 'changed' - but the observer is now coupled to the subject's API, and it must read the state before the next change overwrites it. .NET's events and OnNext are push, and this post stays push from here. Pull earns its place when observers need different slices of the state, or when the state is expensive to copy into every notification.
In real C# code you rarely write that list yourself, because the language already has Observer built in: events. A delegate is a type-safe function pointer; a multicast delegate is a list of them; an event is a multicast delegate with a lock on the door - outside code can subscribe and unsubscribe, but only the owning class can raise it. The same order announcement, the everyday way:
The += is Subscribe. The -= is unsubscribe. The ?.Invoke is Notify, guarded against the case where nobody subscribed. The language gives you the subscriber list and the syntax for free. What it does not give you is a way to say 'I am done sending' or 'something went wrong' - an event has exactly one channel, and it only ever says 'this happened'. And there is a leak hiding in the convenience: a subscription keeps the subscriber alive as long as the publisher lives, because the publisher holds a reference to it. Forget the -= on a long-lived publisher with a short-lived subscriber, and the subscriber is never collected. In a web API, where the publisher usually lives for one request, this rarely bites. In a singleton service or a desktop app, it bites hard.
.NET also has the pattern as a pair of interfaces in the base class library: IObservable<T> is the provider, IObserver<T> is the observer. The provider has exactly one method. The observer has three - one for data, one for errors, one for completion:
That is the complete grammar: zero or more OnNext calls, then exactly one of OnError or OnCompleted, and then silence. Subscribe returns IDisposable, same as the hand-built version - disposing unsubscribes. And the documentation is explicit about one thing it does not guarantee: the interface assumes nothing about how many observers there are or the order they are notified in. If your design needs observers to run in a specific order, Observer is the wrong tool, or you need to build the ordering yourself.
When do you reach for this over an event? When the stream has a lifetime - a feed that ends, a sensor that can fail, a sequence you want to compose. Events are fine for 'this happened'. IObservable<T> is for 'here is a stream of things, and here is how it ends'. Most backend code never needs the formal form, and that is fine. Knowing it exists matters because the day you meet a library built on it, the three methods will already make sense. System.Reactive (Rx) builds LINQ-style operators on top of exactly these two interfaces - Observer, industrialised. You do not need Rx to use the pattern; you need the pattern to understand Rx.
Here is the connection that makes the whole series click. IEnumerable<T> and IObservable<T> are the same grammar with the direction reversed. With IEnumerable, the consumer pulls: MoveNext asks for the next item, Current reads it, an exception escapes from MoveNext, and MoveNext returning false means the sequence ended. With IObservable, the provider pushes: OnNext delivers the next item, OnError delivers the exception, OnCompleted delivers the end. Pull versus push, same three outcomes. Microsoft's Rx documentation calls IObservable<T> the dual of IEnumerable<T> - and once you see it, LINQ's deferred execution and reactive streams stop looking like two different worlds. The Iterator pattern, the pull side, gets its own post next in this series.
The place Observer pays rent in backend code is domain events. An order is placed - that is a fact about the domain, and several unrelated parts of the system care. With MediatR, the fact is a notification, and every reaction is a handler. The publisher names the notification, never the handlers:
This is the Observer pattern wearing application-layer clothes: MediatR is the subject, the handlers are the observers, registration in the container is the subscription. Adding the warehouse Slack message means adding one handler class. The checkout handler does not change, does not grow, and does not know the Slack message exists. That is the same decoupling as the hand-built list, at the scale of a real codebase. My CQRS post introduced MediatR for commands and queries; notifications are its Observer side, and they are the reason a checkout handler can stay boring while the system around it grows.
One caution carries over from the formal form: do not build logic that depends on handlers running in a particular order, or on all of them succeeding together. A notification is a fan-out, not a transaction. If a reaction must happen reliably even when the process crashes - the email must go out, no matter what - that is a job for the Outbox pattern, not for an in-memory notification. Different guarantees, different tool.
The costs are the usual price of indirection:
Invisible reactions. Reading the publisher tells you nothing about what happens next. Finding every reaction means searching for subscribers, and a new developer will miss one.
No ordering, no atomicity. Observers run in an order you should not rely on, and one failing observer does not roll back the others. If the reactions must happen together or not at all, this is not the tool.
Exceptions travel oddly. In an event's invocation list, one throwing handler stops the handlers after it from running. In a hand-built loop, the same, unless you catch per observer. Decide whose failure can break whom before you ship it.
Leaks from forgotten unsubscribes. Every subscription is a reference the publisher holds. Long-lived publisher plus forgotten unsubscribe equals a subscriber that never dies.
So when do you skip it? When there is exactly one reaction and it will always be one - a direct call is simpler, clearer, and easier to trace. When reactions must run in a strict order. When you need delivery guarantees across crashes. Observer is for one-to-many, where the 'many' changes over time. If the 'many' is fixed at one, the pattern is ceremony.
There is one check that settles whether the pattern is doing its job in your code: add a new reaction without touching the publisher. New email, new Slack message, new analytics event - if the publisher's file stays closed, the decoupling is real. If every new reaction means editing the publisher, you have a list of method calls wearing a pattern's name.
Add a new reaction without touching the publisher. If you can, the pattern is doing its job.
Start with the event. It is the form you will use most, and it costs nothing. Reach for IObservable<T> when the stream has a lifetime worth modelling. Reach for MediatR notifications when the reactions live in different parts of the application and the publisher should not know them. And the next time a handler starts collecting method calls for everyone who cares, remember the flip: stop calling everyone. Let them subscribe.
A list of orders in memory, rows streaming out of a database, pages from an API - from the consumer's side they are the same question: give me the next item, and tell me when there are no more. The Iterator pattern is that question answered as an interface pair, and in .NET it is the shape of foreach and LINQ themselves: hand-built enumerators, yield return, deferred execution, and the async twin IAsyncEnumerable<T> - including the costs, and when a List is the honest answer.
An order is placed, and five parts of the system need to know. The Observer pattern flips who knows about whom: the publisher announces one fact, subscribers come and go, and the publisher never changes. From hand-built subjects to C# events, IObservable<T>, and MediatR notifications - with the push and pull models demonstrated in code - including the costs, and when a direct call is the honest answer.
A price is not a decimal, a phone number is not a string, and an email is not a string either. Primitive obsession is the habit of modelling domain concepts with the language's built-in types — and value objects are the small, boring, enormously effective fix.