Observer
An Observer is a fundamental concept in reactive programming, acting as an object that receives notifications from an Observable. It is designed to handle a stream of events, providing a structured way to process data as it is emitted. The Observer object is more complex than a regular iterator but behaves similarly, processing events as they are emitted by the observable.
Structure of an Observer
The Observer object has three main methods:
next(event): This method is called to handle each event in the stream. It processes the data as it arrives.error(e): This method is triggered when an exception occurs somewhere along the observable. It allows the observer to handle errors gracefully.complete(): This method is called when there are no more values to emit. It signifies the end of the data stream and is not called if an error occurs.
[Listing 9.16: Shape of the Observer Object](https://livebook.manning.com/book/the-joy-of-javascript/chapter-9/167)
const Observer = {
next(event) { // #1
//...
},
error(e) { // #2
//...
},
complete() { // #3
//...
}
}
// #1 Receives each event in the stream
// #2 Triggered when an exception occurs somewhere along the observable
// #3 Called when there are no more values to emit; not called on error
Observer in TypeScript
In TypeScript, the Observer can be defined with type semantics to ensure type safety and correctness in stream-based code. This is particularly useful in generic programming, where the type T can be bound to any data type, allowing for flexible and reusable code.
type Observer<T> = {
next: (value: T) => void,
error?: (error: Error) => void,
complete?: () => void
}
Operators and Observers
Operators are functions that transform data streams. They use observers to propagate data through a chain of transformations. Here are some custom operators that utilize observers:
Map Operator
The map operator applies a function to each value emitted by the source observable and notifies observers of any errors.
const map = curry(
(fn, stream) =>
new Observable(observer => {
const subs = stream.subscribe({
next(value) {
try {
observer.next(fn(value));
}
catch (err) {
observer.error(err);
}
},
error(e) {
observer.error(e);
},
complete() {
observer.complete();
}
});
return () => subs.unsubscribe();
});
);
Filter Operator
The filter operator selects which values get propagated based on a predicate function.
const filter = curry(
(predicate, stream) =>
new Observable(observer => {
const subs = stream.subscribe({
next(value) {
if (predicate(value)) {
observer.next(value);
}
},
error(e) {
observer.error(e);
},
complete() {
observer.complete();
}
})
return () => subs.unsubscribe();
});
);
Reduce Operator
The reduce operator folds all the values emitted by a source observable to a single value, which is emitted when the source completes.
const reduce = curry(
(accumulator, initialValue, stream) => {
let result = initialValue ?? {};
return new Observable(observer => {
const subs = stream.subscribe({
next(value) {
result = accumulator(result, value);
},
error(e) {
observer.error(e);
},
complete() {
observer.next(result);
observer.complete();
}
})
return () => subs.unsubscribe();
});
};
);
Skip Operator
The skip operator allows you to ignore the first X number of events from a source observable.
const skip = curry(
(count, stream) => {
let skipped = 0;
return new Observable(observer => {
const subs = stream.subscribe({
next(value) {
if (skipped++ >= count) {
observer.next(value);
}
},
error(e) {
observer.error(e);
},
complete() {
observer.complete();
}
})
return () => subs.unsubscribe();
});
}
);
These operators demonstrate the power and flexibility of using observers in reactive programming, allowing for complex data transformations and handling in a structured and efficient manner.
FAQ (Frequently asked questions)
What is an Observer in JavaScript?
What methods does an Observer have?
How does the next(event) method work in an Observer?
What happens when an error occurs in an Observer?
When is the complete() method called in an Observer?
How does an Observer differ from a regular iterator?
What is the shape of an Observer object?
What does the next(event) method do in an Observer?
When is the error(e) method triggered in an Observer?
What is the purpose of the complete() method in an Observer?