Debian Codegraph @

node/rxjs/src/internal/Subscriber.ts

raw
1 import { isFunction } from './util/isFunction';
2 import { Observer, ObservableNotification } from './types';
3 import { isSubscription, Subscription } from './Subscription';
4 import { config } from './config';
5 import { reportUnhandledError } from './util/reportUnhandledError';
6 import { noop } from './util/noop';
7 import { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';
8 import { timeoutProvider } from './scheduler/timeoutProvider';
9 import { captureError } from './util/errorContext';
10
11 /**
12 * Implements the {@link Observer} interface and extends the
13 * {@link Subscription} class. While the {@link Observer} is the public API for
14 * consuming the values of an {@link Observable}, all Observers get converted to
15 * a Subscriber, in order to provide Subscription-like capabilities such as
16 * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
17 * implementing operators, but it is rarely used as a public API.
18 */
19 export class Subscriber<T> extends Subscription implements Observer<T> {
20 /**
21 * A static factory for a Subscriber, given a (potentially partial) definition
22 * of an Observer.
23 * @param next The `next` callback of an Observer.
24 * @param error The `error` callback of an
25 * Observer.
26 * @param complete The `complete` callback of an
27 * Observer.
28 * @return A Subscriber wrapping the (partially defined)
29 * Observer represented by the given arguments.
30 * @deprecated Do not use. Will be removed in v8. There is no replacement for this
31 * method, and there is no reason to be creating instances of `Subscriber` directly.
32 * If you have a specific use case, please file an issue.
33 */
34 static create<T>(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber<T> {
35 return new SafeSubscriber(next, error, complete);
36 }
37
38 /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
39 protected isStopped: boolean = false;
40 /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
41 protected destination: Subscriber<any> | Observer<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)
42
43 /**
44 * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
45 * There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.
46 */
47 constructor(destination?: Subscriber<any> | Observer<any>) {
48 super();
49 if (destination) {
50 this.destination = destination;
51 // Automatically chain subscriptions together here.
52 // if destination is a Subscription, then it is a Subscriber.
53 if (isSubscription(destination)) {
54 destination.add(this);
55 }
56 } else {
57 this.destination = EMPTY_OBSERVER;
58 }
59 }
60
61 /**
62 * The {@link Observer} callback to receive notifications of type `next` from
63 * the Observable, with a value. The Observable may call this method 0 or more
64 * times.
65 * @param value The `next` value.
66 */
67 next(value: T): void {
68 if (this.isStopped) {
69 handleStoppedNotification(nextNotification(value), this);
70 } else {
71 this._next(value!);
72 }
73 }
74
75 /**
76 * The {@link Observer} callback to receive notifications of type `error` from
77 * the Observable, with an attached `Error`. Notifies the Observer that
78 * the Observable has experienced an error condition.
79 * @param err The `error` exception.
80 */
81 error(err?: any): void {
82 if (this.isStopped) {
83 handleStoppedNotification(errorNotification(err), this);
84 } else {
85 this.isStopped = true;
86 this._error(err);
87 }
88 }
89
90 /**
91 * The {@link Observer} callback to receive a valueless notification of type
92 * `complete` from the Observable. Notifies the Observer that the Observable
93 * has finished sending push-based notifications.
94 */
95 complete(): void {
96 if (this.isStopped) {
97 handleStoppedNotification(COMPLETE_NOTIFICATION, this);
98 } else {
99 this.isStopped = true;
100 this._complete();
101 }
102 }
103
104 unsubscribe(): void {
105 if (!this.closed) {
106 this.isStopped = true;
107 super.unsubscribe();
108 this.destination = null!;
109 }
110 }
111
112 protected _next(value: T): void {
113 this.destination.next(value);
114 }
115
116 protected _error(err: any): void {
117 try {
118 this.destination.error(err);
119 } finally {
120 this.unsubscribe();
121 }
122 }
123
124 protected _complete(): void {
125 try {
126 this.destination.complete();
127 } finally {
128 this.unsubscribe();
129 }
130 }
131 }
132
133 /**
134 * This bind is captured here because we want to be able to have
135 * compatibility with monoid libraries that tend to use a method named
136 * `bind`. In particular, a library called Monio requires this.
137 */
138 const _bind = Function.prototype.bind;
139
140 function bind<Fn extends (...args: any[]) => any>(fn: Fn, thisArg: any): Fn {
141 return _bind.call(fn, thisArg);
142 }
143
144 /**
145 * Internal optimization only, DO NOT EXPOSE.
146 * @internal
147 */
148 class ConsumerObserver<T> implements Observer<T> {
149 constructor(private partialObserver: Partial<Observer<T>>) {}
150
151 next(value: T): void {
152 const { partialObserver } = this;
153 if (partialObserver.next) {
154 try {
155 partialObserver.next(value);
156 } catch (error) {
157 handleUnhandledError(error);
158 }
159 }
160 }
161
162 error(err: any): void {
163 const { partialObserver } = this;
164 if (partialObserver.error) {
165 try {
166 partialObserver.error(err);
167 } catch (error) {
168 handleUnhandledError(error);
169 }
170 } else {
171 handleUnhandledError(err);
172 }
173 }
174
175 complete(): void {
176 const { partialObserver } = this;
177 if (partialObserver.complete) {
178 try {
179 partialObserver.complete();
180 } catch (error) {
181 handleUnhandledError(error);
182 }
183 }
184 }
185 }
186
187 export class SafeSubscriber<T> extends Subscriber<T> {
188 constructor(
189 observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,
190 error?: ((e?: any) => void) | null,
191 complete?: (() => void) | null
192 ) {
193 super();
194
195 let partialObserver: Partial<Observer<T>>;
196 if (isFunction(observerOrNext) || !observerOrNext) {
197 // The first argument is a function, not an observer. The next
198 // two arguments *could* be observers, or they could be empty.
199 partialObserver = {
200 next: (observerOrNext ?? undefined) as ((value: T) => void) | undefined,
201 error: error ?? undefined,
202 complete: complete ?? undefined,
203 };
204 } else {
205 // The first argument is a partial observer.
206 let context: any;
207 if (this && config.useDeprecatedNextContext) {
208 // This is a deprecated path that made `this.unsubscribe()` available in
209 // next handler functions passed to subscribe. This only exists behind a flag
210 // now, as it is *very* slow.
211 context = Object.create(observerOrNext);
212 context.unsubscribe = () => this.unsubscribe();
213 partialObserver = {
214 next: observerOrNext.next && bind(observerOrNext.next, context),
215 error: observerOrNext.error && bind(observerOrNext.error, context),
216 complete: observerOrNext.complete && bind(observerOrNext.complete, context),
217 };
218 } else {
219 // The "normal" path. Just use the partial observer directly.
220 partialObserver = observerOrNext;
221 }
222 }
223
224 // Wrap the partial observer to ensure it's a full observer, and
225 // make sure proper error handling is accounted for.
226 this.destination = new ConsumerObserver(partialObserver);
227 }
228 }
229
230 function handleUnhandledError(error: any) {
231 if (config.useDeprecatedSynchronousErrorHandling) {
232 captureError(error);
233 } else {
234 // Ideal path, we report this as an unhandled error,
235 // which is thrown on a new call stack.
236 reportUnhandledError(error);
237 }
238 }
239
240 /**
241 * An error handler used when no error handler was supplied
242 * to the SafeSubscriber -- meaning no error handler was supplied
243 * do the `subscribe` call on our observable.
244 * @param err The error to handle
245 */
246 function defaultErrorHandler(err: any) {
247 throw err;
248 }
249
250 /**
251 * A handler for notifications that cannot be sent to a stopped subscriber.
252 * @param notification The notification being sent.
253 * @param subscriber The stopped subscriber.
254 */
255 function handleStoppedNotification(notification: ObservableNotification<any>, subscriber: Subscriber<any>) {
256 const { onStoppedNotification } = config;
257 onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));
258 }
259
260 /**
261 * The observer used as a stub for subscriptions where the user did not
262 * pass any arguments to `subscribe`. Comes with the default error handling
263 * behavior.
264 */
265 export const EMPTY_OBSERVER: Readonly<Observer<any>> & { closed: true } = {
266 closed: true,
267 next: noop,
268 error: defaultErrorHandler,
269 complete: noop,
270 };