70. RxJS Observable
Build an Observable with multiple subscribers, errors, and complete
Observables are pivotal in modern application development, especially in asynchronous event-driven architectures. They allow subscribing to a stream of values and receiving notifications for new values, errors, and completion events. This functionality is essential for managing asynchronous data flows and handling events in a decoupled manner.
The real RxJS Observable follows the same subscribe model.
Objective
Your task is to implement a basic Observable class in JavaScript. This class should enable the subscription to a stream of values, supporting multiple subscribers and effectively handling errors and completion events.
RxJS Observable: Requirements
- The class must support multiple subscribers.
- It should handle errors and completion events, delivering these notifications exactly once.
- Subsequent
next, error, or complete calls after an error/complete event should be ignored.
- The
subscribe function should accept either an object with next, error, and complete methods or a function treated as the next method.
- The
subscribe function returns a Subscription object, allowing unsubscribing from the Observable.
Example Usage
Consider the following observer object, indicating its purpose through next, error, and complete callbacks:
const observer = {
next: (value) => { console.log('Received a value:', value); },
error: (error) => { console.log('Encountered an error:', error); },
complete: () => { console.log('No more values to receive.'); }
};
This Observer can be associated with an Observable, which dispatches values, errors, or completion signals to the attached Observer:
const observable = new Observable((subscriber) => {
subscriber.next(1);
subscriber.next(2);
setTimeout(() => {
subscriber.next(3);
subscriber.next(4);
subscriber.complete();
}, 100);
});
Attaching the observer to the observable and handling the subscription allows for receiving values and notifications as defined:
const subscription = observable.subscribe(observer);
// Logs:
// Received a value: 1
// Received a value: 2
// (after delay) Received a value: 3
// Received a value: 4
// No more values to receive.
Follow-Up Problems
This Observable and Observer implementation introduces various intriguing follow-up problems and patterns to explore, further expanding on reactive programming concepts.
Example tests
- should emit values to subscribers
- should handle errors
- should complete observable sequences
Constraints
**Support for Multiple Subscribers**: The Observable should be able to handle multiple subscribers, each with their own set of `next`, `error`, and `complete` callbacks.
**Single Delivery of Error and Completion**: The Observable must ensure that `error` and `complete` notifications are delivered at most once to each subscriber. After an Observable emits an `error` or `complete` notification, it should not emit any further notifications.
**No Further Notifications After Unsubscription**: Once a subscriber has unsubscribed, it should not receive any further notifications, regardless of whether the Observable emits more values or notifications.
**Optional Callbacks**: Not all subscribers will necessarily provide `next`, `error`, and `complete` callbacks. The implementation should account for this by treating any function passed as a subscriber as the `next` callback and gracefully handling the absence of `error` and `complete` methods.
**Immediate Subscription Side Effects**: The subscription logic executed within the Observable's constructor or setup function may have side effects (e.g., emitting values immediately upon subscription). The implementation should ensure these side effects are properly handled.
**Resource Cleanup**: The Observable should provide a mechanism for resource cleanup upon unsubscription, especially for Observables that encapsulate resources like web sockets, intervals, or other subscriptions.
**Error Handling**: The Observable should have a robust error handling mechanism, allowing errors to be caught and processed via the `error` callback of subscribers.
**Completion Signal**: Observables must have a way to signal completion to subscribers, after which no more values will be emitted.
**Immutable Subscription Objects**: The subscription object returned by the `subscribe` method should be immutable, ensuring that subscribers cannot directly modify the state of the subscription.