Back to results for “Design Patterns in C#”
C# › Design Patterns in C#

How would you implement the Observer pattern in C# using events, versus using the IObservable<T>/IObserver<T> interfaces from System?

Advanced

Answer

A simple event-based Observer uses standard C# events (publisher raises an event, subscribers attach handlers) — straightforward but tightly coupled to the delegate/event model. IObservable<T>/IObserver<T> (the Reactive Extensions foundation) formalizes the pattern with an explicit Subscribe()/OnNext()/OnCompleted()/OnError() contract, better suited for composable, LINQ-style event stream processing.
// Event-based
public class StockTicker { public event Action<decimal>? PriceChanged; }

// IObservable-based (more composable, works with Rx operators)
public class StockTickerObservable : IObservable<decimal> {
  public IDisposable Subscribe(IObserver<decimal> observer) { /* ... */ return Disposable.Empty; }
}
Real-world example Choosing plain events for a simple UI click handler versus IObservable<T> for a composable, filterable stream of live stock price updates.

Common follow-ups: What extra composability (like filtering or throttling) does Reactive Extensions (Rx.NET) add on top of raw IObservable<T>?