What is observer?
An observer is a design concept where one piece of code (the observer) watches another piece of code (the subject) and gets notified automatically whenever the subject changes or something important happens.
Let's break it down
- Subject: The object that holds data or state. It knows who is interested in its changes.
- Observer: The object that wants to know when the subject changes. It registers itself with the subject.
- Notification: When the subject’s state changes, it sends a simple message (often called an “event”) to all registered observers so they can react.
Why does it matter?
It lets different parts of a program stay in sync without being tightly coupled. This makes code easier to understand, test, and modify because each part only needs to know how to receive updates, not how the data is produced.
Where is it used?
- User‑interface frameworks (e.g., UI components updating when data changes)
- Real‑time data feeds (stock tickers, chat apps)
- Event‑driven systems like JavaScript’s
addEventListener
or Android’s LiveData - Reactive libraries such as RxJS, Kotlin Flow, or .NET IObservable
Good things about it
- Promotes loose coupling between components
- Simplifies handling of asynchronous or frequent updates
- Makes it easy to add or remove observers at runtime
- Improves code reusability - the same observer can watch many different subjects
Not-so-good things
- Can lead to “memory leaks” if observers are not properly deregistered
- Too many observers may cause performance overhead due to frequent notifications
- Debugging can become harder because the flow of data is indirect and spread across many objects
- Improper implementation may result in race conditions in multithreaded environments.