source: trip-planner-front/node_modules/rxjs/src/internal/Observable.ts@ 188ee53

Last change on this file since 188ee53 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 15.8 KB
Line 
1import { Operator } from './Operator';
2import { Subscriber } from './Subscriber';
3import { Subscription } from './Subscription';
4import { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';
5import { canReportError } from './util/canReportError';
6import { toSubscriber } from './util/toSubscriber';
7import { iif } from './observable/iif';
8import { throwError } from './observable/throwError';
9import { observable as Symbol_observable } from './symbol/observable';
10import { pipeFromArray } from './util/pipe';
11import { config } from './config';
12
13/**
14 * A representation of any set of values over any amount of time. This is the most basic building block
15 * of RxJS.
16 *
17 * @class Observable<T>
18 */
19export class Observable<T> implements Subscribable<T> {
20
21 /** Internal implementation detail, do not use directly. */
22 public _isScalar: boolean = false;
23
24 /** @deprecated This is an internal implementation detail, do not use. */
25 source: Observable<any>;
26
27 /** @deprecated This is an internal implementation detail, do not use. */
28 operator: Operator<any, T>;
29
30 /**
31 * @constructor
32 * @param {Function} subscribe the function that is called when the Observable is
33 * initially subscribed to. This function is given a Subscriber, to which new values
34 * can be `next`ed, or an `error` method can be called to raise an error, or
35 * `complete` can be called to notify of a successful completion.
36 */
37 constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
38 if (subscribe) {
39 this._subscribe = subscribe;
40 }
41 }
42
43 // HACK: Since TypeScript inherits static properties too, we have to
44 // fight against TypeScript here so Subject can have a different static create signature
45 /**
46 * Creates a new cold Observable by calling the Observable constructor
47 * @static true
48 * @owner Observable
49 * @method create
50 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
51 * @return {Observable} a new cold observable
52 * @nocollapse
53 * @deprecated use new Observable() instead
54 */
55 static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {
56 return new Observable<T>(subscribe);
57 }
58
59 /**
60 * Creates a new Observable, with this Observable as the source, and the passed
61 * operator defined as the new observable's operator.
62 * @method lift
63 * @param {Operator} operator the operator defining the operation to take on the observable
64 * @return {Observable} a new observable with the Operator applied
65 */
66 lift<R>(operator: Operator<T, R>): Observable<R> {
67 const observable = new Observable<R>();
68 observable.source = this;
69 observable.operator = operator;
70 return observable;
71 }
72
73 subscribe(observer?: PartialObserver<T>): Subscription;
74 /** @deprecated Use an observer instead of a complete callback */
75 subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;
76 /** @deprecated Use an observer instead of an error callback */
77 subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;
78 /** @deprecated Use an observer instead of a complete callback */
79 subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;
80 subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
81 /**
82 * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
83 *
84 * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
85 *
86 * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
87 * might be for example a function that you passed to Observable's constructor, but most of the time it is
88 * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means
89 * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
90 * the thought.
91 *
92 * Apart from starting the execution of an Observable, this method allows you to listen for values
93 * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
94 * of the following ways.
95 *
96 * The first way is creating an object that implements {@link Observer} interface. It should have methods
97 * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
98 * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
99 * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
100 * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
101 * do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will
102 * be left uncaught.
103 *
104 * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
105 * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent
106 * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,
107 * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
108 * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
109 * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
110 *
111 * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.
112 * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean
113 * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
114 * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
115 *
116 * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
117 * It is an Observable itself that decides when these functions will be called. For example {@link of}
118 * by default emits all its values synchronously. Always check documentation for how given Observable
119 * will behave when subscribed and if its default behavior can be modified with a `scheduler`.
120 *
121 * ## Example
122 * ### Subscribe with an Observer
123 * ```ts
124 * import { of } from 'rxjs';
125 *
126 * const sumObserver = {
127 * sum: 0,
128 * next(value) {
129 * console.log('Adding: ' + value);
130 * this.sum = this.sum + value;
131 * },
132 * error() {
133 * // We actually could just remove this method,
134 * // since we do not really care about errors right now.
135 * },
136 * complete() {
137 * console.log('Sum equals: ' + this.sum);
138 * }
139 * };
140 *
141 * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
142 * .subscribe(sumObserver);
143 *
144 * // Logs:
145 * // "Adding: 1"
146 * // "Adding: 2"
147 * // "Adding: 3"
148 * // "Sum equals: 6"
149 * ```
150 *
151 * ### Subscribe with functions
152 * ```ts
153 * import { of } from 'rxjs'
154 *
155 * let sum = 0;
156 *
157 * of(1, 2, 3).subscribe(
158 * value => {
159 * console.log('Adding: ' + value);
160 * sum = sum + value;
161 * },
162 * undefined,
163 * () => console.log('Sum equals: ' + sum)
164 * );
165 *
166 * // Logs:
167 * // "Adding: 1"
168 * // "Adding: 2"
169 * // "Adding: 3"
170 * // "Sum equals: 6"
171 * ```
172 *
173 * ### Cancel a subscription
174 * ```ts
175 * import { interval } from 'rxjs';
176 *
177 * const subscription = interval(1000).subscribe(
178 * num => console.log(num),
179 * undefined,
180 * () => {
181 * // Will not be called, even when cancelling subscription.
182 * console.log('completed!');
183 * }
184 * );
185 *
186 * setTimeout(() => {
187 * subscription.unsubscribe();
188 * console.log('unsubscribed!');
189 * }, 2500);
190 *
191 * // Logs:
192 * // 0 after 1s
193 * // 1 after 2s
194 * // "unsubscribed!" after 2.5s
195 * ```
196 *
197 * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
198 * or the first of three possible handlers, which is the handler for each value emitted from the subscribed
199 * Observable.
200 * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
201 * the error will be thrown as unhandled.
202 * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
203 * @return {ISubscription} a subscription reference to the registered handlers
204 * @method subscribe
205 */
206 subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),
207 error?: (error: any) => void,
208 complete?: () => void): Subscription {
209
210 const { operator } = this;
211 const sink = toSubscriber(observerOrNext, error, complete);
212
213 if (operator) {
214 sink.add(operator.call(sink, this.source));
215 } else {
216 sink.add(
217 this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
218 this._subscribe(sink) :
219 this._trySubscribe(sink)
220 );
221 }
222
223 if (config.useDeprecatedSynchronousErrorHandling) {
224 if (sink.syncErrorThrowable) {
225 sink.syncErrorThrowable = false;
226 if (sink.syncErrorThrown) {
227 throw sink.syncErrorValue;
228 }
229 }
230 }
231
232 return sink;
233 }
234
235 /** @deprecated This is an internal implementation detail, do not use. */
236 _trySubscribe(sink: Subscriber<T>): TeardownLogic {
237 try {
238 return this._subscribe(sink);
239 } catch (err) {
240 if (config.useDeprecatedSynchronousErrorHandling) {
241 sink.syncErrorThrown = true;
242 sink.syncErrorValue = err;
243 }
244 if (canReportError(sink)) {
245 sink.error(err);
246 } else {
247 console.warn(err);
248 }
249 }
250 }
251
252 /**
253 * @method forEach
254 * @param {Function} next a handler for each value emitted by the observable
255 * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise
256 * @return {Promise} a promise that either resolves on observable completion or
257 * rejects with the handled error
258 */
259 forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {
260 promiseCtor = getPromiseCtor(promiseCtor);
261
262 return new promiseCtor<void>((resolve, reject) => {
263 // Must be declared in a separate statement to avoid a ReferenceError when
264 // accessing subscription below in the closure due to Temporal Dead Zone.
265 let subscription: Subscription;
266 subscription = this.subscribe((value) => {
267 try {
268 next(value);
269 } catch (err) {
270 reject(err);
271 if (subscription) {
272 subscription.unsubscribe();
273 }
274 }
275 }, reject, resolve);
276 }) as Promise<void>;
277 }
278
279 /** @internal This is an internal implementation detail, do not use. */
280 _subscribe(subscriber: Subscriber<any>): TeardownLogic {
281 const { source } = this;
282 return source && source.subscribe(subscriber);
283 }
284
285 // `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in
286 // favor of iif and throwError functions.
287 /**
288 * @nocollapse
289 * @deprecated In favor of iif creation function: import { iif } from 'rxjs';
290 */
291 static if: typeof iif;
292 /**
293 * @nocollapse
294 * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';
295 */
296 static throw: typeof throwError;
297
298 /**
299 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
300 * @method Symbol.observable
301 * @return {Observable} this instance of the observable
302 */
303 [Symbol_observable]() {
304 return this;
305 }
306
307 /* tslint:disable:max-line-length */
308 pipe(): Observable<T>;
309 pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;
310 pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;
311 pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;
312 pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;
313 pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>;
314 pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>;
315 pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>;
316 pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>;
317 pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>;
318 pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>;
319 /* tslint:enable:max-line-length */
320
321 /**
322 * Used to stitch together functional operators into a chain.
323 * @method pipe
324 * @return {Observable} the Observable result of all of the operators having
325 * been called in the order they were passed in.
326 *
327 * ### Example
328 * ```ts
329 * import { interval } from 'rxjs';
330 * import { map, filter, scan } from 'rxjs/operators';
331 *
332 * interval(1000)
333 * .pipe(
334 * filter(x => x % 2 === 0),
335 * map(x => x + x),
336 * scan((acc, x) => acc + x)
337 * )
338 * .subscribe(x => console.log(x))
339 * ```
340 */
341 pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {
342 if (operations.length === 0) {
343 return this as any;
344 }
345
346 return pipeFromArray(operations)(this);
347 }
348
349 /* tslint:disable:max-line-length */
350 toPromise<T>(this: Observable<T>): Promise<T>;
351 toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;
352 toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;
353 /* tslint:enable:max-line-length */
354
355 toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {
356 promiseCtor = getPromiseCtor(promiseCtor);
357
358 return new promiseCtor((resolve, reject) => {
359 let value: any;
360 this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));
361 }) as Promise<T>;
362 }
363}
364
365/**
366 * Decides between a passed promise constructor from consuming code,
367 * A default configured promise constructor, and the native promise
368 * constructor and returns it. If nothing can be found, it will throw
369 * an error.
370 * @param promiseCtor The optional promise constructor to passed by consuming code
371 */
372function getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {
373 if (!promiseCtor) {
374 promiseCtor = config.Promise || Promise;
375 }
376
377 if (!promiseCtor) {
378 throw new Error('no Promise impl found');
379 }
380
381 return promiseCtor;
382}
Note: See TracBrowser for help on using the repository browser.