I. Reactive Programming
1. What Is Reactive Programming
Reactive programming is a programming paradigm oriented around data change and the propagation of that change.
Its core idea is to treat data changes as observable signals, so that when data changes, the computations and processing logic that depend on that data can respond automatically.
Traditional imperative programming usually has the developer explicitly control the update process:
let price = 100;
let quantity = 2;
let total = price * quantity;
price = 120;
// Must manually recompute
total = price * quantity;
console.log(total); // 240
Reactive programming, by contrast, emphasizes establishing dependencies between data, so that derived data updates as its source data changes.
Conceptually:
price ─────┐
├──> total
quantity ──┘
This relationship means that total depends on price and quantity. When either dependency changes, the system can trigger a recomputation.
2. Core Components of a Reactive System
A typical reactive system usually consists of the following parts:
| Component | Role |
|---|---|
| Data source (Source) | Provides initial values or continuously changing data |
| Observable | Represents a data stream that can be subscribed to |
| Subscriber | Receives data changes and performs processing |
| Operator | Transforms, filters, and combines data streams |
| Scheduler | Controls when tasks execute and the scheduling strategy |
| Dependency tracking | Records the dependencies between data and computation logic |
Not all reactive frameworks adopt exactly the same implementation structure. For example, signal-based systems usually track state dependencies directly, while stream-based systems such as RxJS center on Observables and the subscription mechanism.
3. Reactive Data Propagation Mechanism
A reactive system typically needs to accomplish dependency establishment, change detection, dependency notification, and derived computation.
flowchart TD
A["Create data source"] --> B["Establish dependencies"]
B --> C["Subscribe to or track dependencies"]
C --> D["Source data changes"]
D --> E["Detect change"]
E --> F["Notify dependent nodes"]
F --> G["Recompute or execute callbacks"]
G --> H["Update downstream state or view"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that being reactive does not mean all dependent logic executes synchronously and immediately on every data change. The exact timing depends on the framework's scheduling strategy, which may involve batching, microtasks, macrotasks, or lazy computation.
4. Reactive Data and Dependency Tracking
An important capability of a reactive system is automatically establishing data dependencies.
For example:
const state = {
price: 100,
quantity: 2
};
function getTotal() {
return state.price * state.quantity;
}
With a reactive system, executing getTotal() can record which reactive properties it read.
When price or quantity updates, the system then knows that the related computation needs to be re-executed.
The dependency relationship can be abstracted as:
flowchart TD
A["price"] --> C["getTotal"]
B["quantity"] --> C
C --> D["total"]
D --> E["View update"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
In JavaScript, simple property access tracking can be implemented through Proxy:
const dependencies = new Map();
let activeEffect = null;
function reactive(target) {
return new Proxy(target, {
get(obj, key) {
if (activeEffect) {
let effects = dependencies.get(key);
if (!effects) {
effects = new Set();
dependencies.set(key, effects);
}
effects.add(activeEffect);
}
return obj[key];
},
set(obj, key, value) {
obj[key] = value;
const effects = dependencies.get(key);
if (effects) {
effects.forEach(effect => effect());
}
return true;
}
});
}
function effect(fn) {
activeEffect = fn;
fn();
activeEffect = null;
}
const state = reactive({
price: 100,
quantity: 2
});
effect(() => {
console.log(state.price * state.quantity);
});
state.price = 120;
This simplified example demonstrates the basic idea of dependency collection and triggering updates.
A production-grade reactive system also needs to handle:
- Dependency isolation when multiple objects have properties with the same name.
- Dependency tracking for nested objects and arrays.
- Dynamic dependency changes caused by conditional branches.
- Deleting properties and adding properties.
- Context restoration for nested effects.
- Circular updates and repeated triggering.
- Batch scheduling and update order.
For example, the above example uses only property names as dependency keys. Properties with the same name on different objects will create incorrect dependency associations, so it cannot be used directly in a production environment.
5. Reactive Data Flow
Reactive programming can handle not only changes to a single variable, but also organize continuous data changes into data streams (Data Stream).
Data streams can represent:
- User input.
- Mouse movement.
- Network request results.
- Timer signals.
- Message queue data.
- Sensor data.
- Real-time business events.
For example, using RxJS:
import { fromEvent } from "rxjs";
import { map, filter } from "rxjs/operators";
const clicks = fromEvent(
document,
"click"
);
const positions = clicks.pipe(
map(event => ({
x: event.clientX,
y: event.clientY
})),
filter(position => position.x > 100)
);
const subscription = positions.subscribe(position => {
console.log(position);
});
Here:
fromEventconverts DOM events into Observables.mapconverts raw events into coordinate data.filterfilters out data that does not meet the condition.subscriberegisters a data stream consumer.
The advantage of data stream processing is that complex asynchronous processing logic can be built up step by step through operators.
6. Main Characteristics of Reactive Programming
Declarative data relationships
Developers describe data dependencies and transformation rules, instead of manually updating all associated states at every point where data is modified.
Automatic dependency propagation
When data changes, the system notifies dependent computations or subscribers based on dependency relationships.
Asynchronous Data Processing
It can uniformly handle asynchronous data sources such as timers, network requests, user input, and message events.
Data Flow Composition
Build complex data processing pipelines through operators such as mapping, filtering, merging, and throttling.
Execution Scheduling
The system can control update timing and supports batch processing, delayed execution, and concurrent scheduling.
II. Event-Driven Programming
1. What Is Event-Driven Programming
Event-driven programming is a programming model in which the occurrence of events serves as the trigger condition for program execution.
An event represents some fact or state change that occurs in the system, for example:
- The user clicks a button.
- An HTTP request arrives.
- A timer fires.
- A file read completes.
- A database connection is disconnected.
- A message queue receives a message.
- An order status changes.
The program does not need to actively poll all possible situations in a fixed order; instead, it registers event handling logic and executes the corresponding operation when an event arrives.
For example:
const button = document.querySelector("#submit");
button.addEventListener("click", () => {
console.log("按钮被点击");
});
Here:
clickis the event type.addEventListenerregisters an event listener.- The callback function is the event handler.
- When the user clicks the button, the browser triggers the event handling process.
2. Core Components of an Event-Driven System
| Component | Role |
|---|---|
| Event Source | Entity that generates events |
| Event | Describes the fact that occurred |
| Event Listener | Listens for specified types of events |
| Event Handler | Receives events and executes business logic |
| Event Dispatcher | Dispatches events to the corresponding handlers |
| Event Queue | Temporarily stores events waiting to be processed |
| Event Loop | Coordinates the execution of events and tasks |
Different systems do not necessarily include all these components.
For example, browser DOM events have an event propagation mechanism, while a backend system driven by a message queue may consist of a Broker, a Consumer, and a message acknowledgment mechanism.
3. Basic Execution Flow of Event-Driven Programming
flowchart TD
A["Event source produces event"] --> B["Event enters dispatch mechanism"]
B --> C["Match listener"]
C --> D["Invoke event handler"]
D --> E{"Processing succeeded?"}
E -->|"Yes"| F["Complete event handling"]
E -->|"No"| G["Execute exception handling"]
G --> H["Log error or retry"]
H --> I["End or redeliver"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The key to the event-driven model is the association between events and handling logic, not the necessity of having an independent event queue.
4. Event Listening and Handling
In JavaScript, you can use EventTarget to implement event listening.
const eventTarget = new EventTarget();
function handleOrderCreated(event) {
console.log("订单创建成功:", event.detail);
}
eventTarget.addEventListener(
"orderCreated",
handleOrderCreated
);
const event = new CustomEvent("orderCreated", {
detail: {
orderId: 1001,
amount: 299
}
});
eventTarget.dispatchEvent(event);
Here, custom events separate the event producer from the handling logic.
The event producer is only responsible for publishing events and does not need to know directly who handles them.
5. Publish-Subscribe Pattern
The publish-subscribe pattern is a common design pattern in event-driven programming.
It establishes an indirect relationship between publishers and subscribers through event topics or message channels.
- Publisher: publishes events.
- Subscriber: subscribes to events of interest.
- Event Bus: receives and dispatches events.
For example:
class EventBus {
constructor() {
this.events = new Map();
}
on(type, handler) {
if (!this.events.has(type)) {
this.events.set(type, new Set());
}
this.events.get(type).add(handler);
}
emit(type, data) {
const handlers = this.events.get(type);
if (!handlers) {
return;
}
handlers.forEach(handler => handler(data));
}
off(type, handler) {
this.events.get(type)?.delete(handler);
}
}
const bus = new EventBus();
bus.on("orderCreated", data => {
console.log("通知库存服务", data);
});
bus.on("orderCreated", data => {
console.log("通知消息服务", data);
});
bus.emit("orderCreated", {
orderId: 1001
});
A single event can be received by multiple subscribers, enabling one-to-many message distribution.
Note that the implementation above is a synchronous in-memory event bus and does not provide capabilities such as persistence, cross-process transport, message acknowledgement, or failure retry.
6. Event-Driven Programming and the Event Loop
In JavaScript browser environments and Node.js, the event loop is an important mechanism for scheduling asynchronous tasks.
Taking the browser environment as an example, the main components involved are:
- Call Stack.
- Web APIs provided by the browser.
- Task Queue.
- Microtask Queue.
- Event loop scheduling.
Typical execution relationship:
flowchart TD
A["Execute synchronous code"] --> B["Call stack execution completes"]
B --> C["Execute microtask queue"]
C --> D{"Are there any remaining microtasks?"}
D -->|"Yes"| C
D -->|"No"| E["Browser gets an opportunity to render"]
E --> F["Execute the next macrotask"]
F --> G["Check the microtask queue"]
G --> C
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Pay special attention here:
- Synchronous code executes in the current call stack.
- After the current task ends, the browser performs a microtask checkpoint.
- Microtasks typically include Promise callbacks and tasks registered with
queueMicrotask. - The browser performs rendering at an appropriate time.
- It then continues processing subsequent tasks.
This process is a simplified model of the browser event loop. Node.js differs from the browser in its event loop phases, scheduling rules, and rendering mechanism, so the browser's complete execution order cannot be applied directly.
III. Differences Between Reactive Programming and Event-Driven Programming
The two are often used together, but their concerns are not the same.
1. Core Differences
| Comparison Dimension | Reactive Programming | Event-Driven Programming |
|---|---|---|
| Core focus | Data changes and propagation | Event occurrence and handling |
| Basic abstraction | Data streams, state, dependencies | Events, listeners, handlers |
| Trigger basis | Changes in data sources | Events being triggered |
| Processing approach | Transformation, filtering, combination, propagation | Dispatch, listening, handler execution |
| Typical scenarios | State management, real-time data streams | User interaction, message processing |
| Common technologies | RxJS, Reactor, Signals | DOM Events, EventEmitter, message queues |
| Design goal | Manage relationships between data changes | Decouple event production from event handling |
2. Relationship Between the Two
Reactive programming can use events as data sources, and event-driven systems can also use reactive data streams to process events.
For example:
flowchart TD
A["User clicks button"] --> B["Generate Click event"]
B --> C["Convert to reactive data stream"]
C --> D["Filter invalid events"]
D --> E["Perform data transformation"]
E --> F["Update application state"]
F --> G["Trigger view update"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Combining the two can simultaneously provide:
- Decoupling between event production and business processing.
- Automatic propagation of data changes.
- Capabilities for transforming and combining data streams.
- Unified management of asynchronous processing.
IV. Typical Implementation Mechanisms of Reactive Programming
Different reactive frameworks adopt somewhat different implementation approaches, but common mechanisms include dependency tracking, subscription notification, data stream operations, and scheduled execution.
1. Observer Pattern
The observer pattern maintains a list of observers so that a change in one object's state can notify multiple observers.
Basic structure:
- Subject: the observed object.
- Observer: the observer.
- Notify: the notification mechanism.
- Update: the observer's update behavior.
class Subject {
constructor() {
this.observers = new Set();
}
subscribe(observer) {
this.observers.add(observer);
}
unsubscribe(observer) {
this.observers.delete(observer);
}
notify(data) {
this.observers.forEach(observer => {
observer.update(data);
});
}
}
class Observer {
update(data) {
console.log("收到更新:", data);
}
}
const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();
subject.subscribe(observer1);
subject.subscribe(observer2);
subject.notify({
value: 100
});
The observer pattern is suitable for implementing one-to-many notification relationships.