136cffbf6ee93510760d1dd1f198be3907f675ccc28af311d709443b70cafb4359fdadc5a5e1ddc3119c6e4299af35e85ee7d39c4001f8ba7becfd898b5477 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. import { Operator } from './Operator';
  2. import { SafeSubscriber, Subscriber } from './Subscriber';
  3. import { isSubscription, Subscription } from './Subscription';
  4. import { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';
  5. import { observable as Symbol_observable } from './symbol/observable';
  6. import { pipeFromArray } from './util/pipe';
  7. import { config } from './config';
  8. import { isFunction } from './util/isFunction';
  9. import { errorContext } from './util/errorContext';
  10. /**
  11. * A representation of any set of values over any amount of time. This is the most basic building block
  12. * of RxJS.
  13. */
  14. export class Observable<T> implements Subscribable<T> {
  15. /**
  16. * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
  17. */
  18. source: Observable<any> | undefined;
  19. /**
  20. * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
  21. */
  22. operator: Operator<any, T> | undefined;
  23. /**
  24. * @param subscribe The function that is called when the Observable is
  25. * initially subscribed to. This function is given a Subscriber, to which new values
  26. * can be `next`ed, or an `error` method can be called to raise an error, or
  27. * `complete` can be called to notify of a successful completion.
  28. */
  29. constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
  30. if (subscribe) {
  31. this._subscribe = subscribe;
  32. }
  33. }
  34. // HACK: Since TypeScript inherits static properties too, we have to
  35. // fight against TypeScript here so Subject can have a different static create signature
  36. /**
  37. * Creates a new Observable by calling the Observable constructor
  38. * @param subscribe the subscriber function to be passed to the Observable constructor
  39. * @return A new observable.
  40. * @deprecated Use `new Observable()` instead. Will be removed in v8.
  41. */
  42. static create: (...args: any[]) => any = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {
  43. return new Observable<T>(subscribe);
  44. };
  45. /**
  46. * Creates a new Observable, with this Observable instance as the source, and the passed
  47. * operator defined as the new observable's operator.
  48. * @param operator the operator defining the operation to take on the observable
  49. * @return A new observable with the Operator applied.
  50. * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
  51. * If you have implemented an operator using `lift`, it is recommended that you create an
  52. * operator by simply returning `new Observable()` directly. See "Creating new operators from
  53. * scratch" section here: https://rxjs.dev/guide/operators
  54. */
  55. lift<R>(operator?: Operator<T, R>): Observable<R> {
  56. const observable = new Observable<R>();
  57. observable.source = this;
  58. observable.operator = operator;
  59. return observable;
  60. }
  61. subscribe(observerOrNext?: Partial<Observer<T>> | ((value: T) => void)): Subscription;
  62. /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */
  63. subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;
  64. /**
  65. * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
  66. *
  67. * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
  68. *
  69. * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
  70. * might be for example a function that you passed to Observable's constructor, but most of the time it is
  71. * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means
  72. * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
  73. * the thought.
  74. *
  75. * Apart from starting the execution of an Observable, this method allows you to listen for values
  76. * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
  77. * of the following ways.
  78. *
  79. * The first way is creating an object that implements {@link Observer} interface. It should have methods
  80. * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
  81. * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do
  82. * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
  83. * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
  84. * do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,
  85. * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,
  86. * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or
  87. * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide
  88. * an `error` method to avoid missing thrown errors.
  89. *
  90. * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
  91. * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent
  92. * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,
  93. * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,
  94. * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
  95. * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.
  96. *
  97. * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events
  98. * and you also handled emissions internally by using operators (e.g. using `tap`).
  99. *
  100. * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.
  101. * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean
  102. * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
  103. * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
  104. *
  105. * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
  106. * It is an Observable itself that decides when these functions will be called. For example {@link of}
  107. * by default emits all its values synchronously. Always check documentation for how given Observable
  108. * will behave when subscribed and if its default behavior can be modified with a `scheduler`.
  109. *
  110. * #### Examples
  111. *
  112. * Subscribe with an {@link guide/observer Observer}
  113. *
  114. * ```ts
  115. * import { of } from 'rxjs';
  116. *
  117. * const sumObserver = {
  118. * sum: 0,
  119. * next(value) {
  120. * console.log('Adding: ' + value);
  121. * this.sum = this.sum + value;
  122. * },
  123. * error() {
  124. * // We actually could just remove this method,
  125. * // since we do not really care about errors right now.
  126. * },
  127. * complete() {
  128. * console.log('Sum equals: ' + this.sum);
  129. * }
  130. * };
  131. *
  132. * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
  133. * .subscribe(sumObserver);
  134. *
  135. * // Logs:
  136. * // 'Adding: 1'
  137. * // 'Adding: 2'
  138. * // 'Adding: 3'
  139. * // 'Sum equals: 6'
  140. * ```
  141. *
  142. * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})
  143. *
  144. * ```ts
  145. * import { of } from 'rxjs'
  146. *
  147. * let sum = 0;
  148. *
  149. * of(1, 2, 3).subscribe(
  150. * value => {
  151. * console.log('Adding: ' + value);
  152. * sum = sum + value;
  153. * },
  154. * undefined,
  155. * () => console.log('Sum equals: ' + sum)
  156. * );
  157. *
  158. * // Logs:
  159. * // 'Adding: 1'
  160. * // 'Adding: 2'
  161. * // 'Adding: 3'
  162. * // 'Sum equals: 6'
  163. * ```
  164. *
  165. * Cancel a subscription
  166. *
  167. * ```ts
  168. * import { interval } from 'rxjs';
  169. *
  170. * const subscription = interval(1000).subscribe({
  171. * next(num) {
  172. * console.log(num)
  173. * },
  174. * complete() {
  175. * // Will not be called, even when cancelling subscription.
  176. * console.log('completed!');
  177. * }
  178. * });
  179. *
  180. * setTimeout(() => {
  181. * subscription.unsubscribe();
  182. * console.log('unsubscribed!');
  183. * }, 2500);
  184. *
  185. * // Logs:
  186. * // 0 after 1s
  187. * // 1 after 2s
  188. * // 'unsubscribed!' after 2.5s
  189. * ```
  190. *
  191. * @param observerOrNext Either an {@link Observer} with some or all callback methods,
  192. * or the `next` handler that is called for each value emitted from the subscribed Observable.
  193. * @param error A handler for a terminal event resulting from an error. If no error handler is provided,
  194. * the error will be thrown asynchronously as unhandled.
  195. * @param complete A handler for a terminal event resulting from successful completion.
  196. * @return A subscription reference to the registered handlers.
  197. */
  198. subscribe(
  199. observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,
  200. error?: ((error: any) => void) | null,
  201. complete?: (() => void) | null
  202. ): Subscription {
  203. const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
  204. errorContext(() => {
  205. const { operator, source } = this;
  206. subscriber.add(
  207. operator
  208. ? // We're dealing with a subscription in the
  209. // operator chain to one of our lifted operators.
  210. operator.call(subscriber, source)
  211. : source
  212. ? // If `source` has a value, but `operator` does not, something that
  213. // had intimate knowledge of our API, like our `Subject`, must have
  214. // set it. We're going to just call `_subscribe` directly.
  215. this._subscribe(subscriber)
  216. : // In all other cases, we're likely wrapping a user-provided initializer
  217. // function, so we need to catch errors and handle them appropriately.
  218. this._trySubscribe(subscriber)
  219. );
  220. });
  221. return subscriber;
  222. }
  223. /** @internal */
  224. protected _trySubscribe(sink: Subscriber<T>): TeardownLogic {
  225. try {
  226. return this._subscribe(sink);
  227. } catch (err) {
  228. // We don't need to return anything in this case,
  229. // because it's just going to try to `add()` to a subscription
  230. // above.
  231. sink.error(err);
  232. }
  233. }
  234. /**
  235. * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with
  236. * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.
  237. *
  238. * **WARNING**: Only use this with observables you *know* will complete. If the source
  239. * observable does not complete, you will end up with a promise that is hung up, and
  240. * potentially all of the state of an async function hanging out in memory. To avoid
  241. * this situation, look into adding something like {@link timeout}, {@link take},
  242. * {@link takeWhile}, or {@link takeUntil} amongst others.
  243. *
  244. * #### Example
  245. *
  246. * ```ts
  247. * import { interval, take } from 'rxjs';
  248. *
  249. * const source$ = interval(1000).pipe(take(4));
  250. *
  251. * async function getTotal() {
  252. * let total = 0;
  253. *
  254. * await source$.forEach(value => {
  255. * total += value;
  256. * console.log('observable -> ' + value);
  257. * });
  258. *
  259. * return total;
  260. * }
  261. *
  262. * getTotal().then(
  263. * total => console.log('Total: ' + total)
  264. * );
  265. *
  266. * // Expected:
  267. * // 'observable -> 0'
  268. * // 'observable -> 1'
  269. * // 'observable -> 2'
  270. * // 'observable -> 3'
  271. * // 'Total: 6'
  272. * ```
  273. *
  274. * @param next A handler for each value emitted by the observable.
  275. * @return A promise that either resolves on observable completion or
  276. * rejects with the handled error.
  277. */
  278. forEach(next: (value: T) => void): Promise<void>;
  279. /**
  280. * @param next a handler for each value emitted by the observable
  281. * @param promiseCtor a constructor function used to instantiate the Promise
  282. * @return a promise that either resolves on observable completion or
  283. * rejects with the handled error
  284. * @deprecated Passing a Promise constructor will no longer be available
  285. * in upcoming versions of RxJS. This is because it adds weight to the library, for very
  286. * little benefit. If you need this functionality, it is recommended that you either
  287. * polyfill Promise, or you create an adapter to convert the returned native promise
  288. * to whatever promise implementation you wanted. Will be removed in v8.
  289. */
  290. forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise<void>;
  291. forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {
  292. promiseCtor = getPromiseCtor(promiseCtor);
  293. return new promiseCtor<void>((resolve, reject) => {
  294. const subscriber = new SafeSubscriber<T>({
  295. next: (value) => {
  296. try {
  297. next(value);
  298. } catch (err) {
  299. reject(err);
  300. subscriber.unsubscribe();
  301. }
  302. },
  303. error: reject,
  304. complete: resolve,
  305. });
  306. this.subscribe(subscriber);
  307. }) as Promise<void>;
  308. }
  309. /** @internal */
  310. protected _subscribe(subscriber: Subscriber<any>): TeardownLogic {
  311. return this.source?.subscribe(subscriber);
  312. }
  313. /**
  314. * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
  315. * @return This instance of the observable.
  316. */
  317. [Symbol_observable]() {
  318. return this;
  319. }
  320. /* tslint:disable:max-line-length */
  321. pipe(): Observable<T>;
  322. pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;
  323. pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;
  324. pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;
  325. pipe<A, B, C, D>(
  326. op1: OperatorFunction<T, A>,
  327. op2: OperatorFunction<A, B>,
  328. op3: OperatorFunction<B, C>,
  329. op4: OperatorFunction<C, D>
  330. ): Observable<D>;
  331. pipe<A, B, C, D, E>(
  332. op1: OperatorFunction<T, A>,
  333. op2: OperatorFunction<A, B>,
  334. op3: OperatorFunction<B, C>,
  335. op4: OperatorFunction<C, D>,
  336. op5: OperatorFunction<D, E>
  337. ): Observable<E>;
  338. pipe<A, B, C, D, E, F>(
  339. op1: OperatorFunction<T, A>,
  340. op2: OperatorFunction<A, B>,
  341. op3: OperatorFunction<B, C>,
  342. op4: OperatorFunction<C, D>,
  343. op5: OperatorFunction<D, E>,
  344. op6: OperatorFunction<E, F>
  345. ): Observable<F>;
  346. pipe<A, B, C, D, E, F, G>(
  347. op1: OperatorFunction<T, A>,
  348. op2: OperatorFunction<A, B>,
  349. op3: OperatorFunction<B, C>,
  350. op4: OperatorFunction<C, D>,
  351. op5: OperatorFunction<D, E>,
  352. op6: OperatorFunction<E, F>,
  353. op7: OperatorFunction<F, G>
  354. ): Observable<G>;
  355. pipe<A, B, C, D, E, F, G, H>(
  356. op1: OperatorFunction<T, A>,
  357. op2: OperatorFunction<A, B>,
  358. op3: OperatorFunction<B, C>,
  359. op4: OperatorFunction<C, D>,
  360. op5: OperatorFunction<D, E>,
  361. op6: OperatorFunction<E, F>,
  362. op7: OperatorFunction<F, G>,
  363. op8: OperatorFunction<G, H>
  364. ): Observable<H>;
  365. pipe<A, B, C, D, E, F, G, H, I>(
  366. op1: OperatorFunction<T, A>,
  367. op2: OperatorFunction<A, B>,
  368. op3: OperatorFunction<B, C>,
  369. op4: OperatorFunction<C, D>,
  370. op5: OperatorFunction<D, E>,
  371. op6: OperatorFunction<E, F>,
  372. op7: OperatorFunction<F, G>,
  373. op8: OperatorFunction<G, H>,
  374. op9: OperatorFunction<H, I>
  375. ): Observable<I>;
  376. pipe<A, B, C, D, E, F, G, H, I>(
  377. op1: OperatorFunction<T, A>,
  378. op2: OperatorFunction<A, B>,
  379. op3: OperatorFunction<B, C>,
  380. op4: OperatorFunction<C, D>,
  381. op5: OperatorFunction<D, E>,
  382. op6: OperatorFunction<E, F>,
  383. op7: OperatorFunction<F, G>,
  384. op8: OperatorFunction<G, H>,
  385. op9: OperatorFunction<H, I>,
  386. ...operations: OperatorFunction<any, any>[]
  387. ): Observable<unknown>;
  388. /* tslint:enable:max-line-length */
  389. /**
  390. * Used to stitch together functional operators into a chain.
  391. *
  392. * ## Example
  393. *
  394. * ```ts
  395. * import { interval, filter, map, scan } from 'rxjs';
  396. *
  397. * interval(1000)
  398. * .pipe(
  399. * filter(x => x % 2 === 0),
  400. * map(x => x + x),
  401. * scan((acc, x) => acc + x)
  402. * )
  403. * .subscribe(x => console.log(x));
  404. * ```
  405. *
  406. * @return The Observable result of all the operators having been called
  407. * in the order they were passed in.
  408. */
  409. pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {
  410. return pipeFromArray(operations)(this);
  411. }
  412. /* tslint:disable:max-line-length */
  413. /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
  414. toPromise(): Promise<T | undefined>;
  415. /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
  416. toPromise(PromiseCtor: typeof Promise): Promise<T | undefined>;
  417. /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
  418. toPromise(PromiseCtor: PromiseConstructorLike): Promise<T | undefined>;
  419. /* tslint:enable:max-line-length */
  420. /**
  421. * Subscribe to this Observable and get a Promise resolving on
  422. * `complete` with the last emission (if any).
  423. *
  424. * **WARNING**: Only use this with observables you *know* will complete. If the source
  425. * observable does not complete, you will end up with a promise that is hung up, and
  426. * potentially all of the state of an async function hanging out in memory. To avoid
  427. * this situation, look into adding something like {@link timeout}, {@link take},
  428. * {@link takeWhile}, or {@link takeUntil} amongst others.
  429. *
  430. * @param [promiseCtor] a constructor function used to instantiate
  431. * the Promise
  432. * @return A Promise that resolves with the last value emit, or
  433. * rejects on an error. If there were no emissions, Promise
  434. * resolves with undefined.
  435. * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise
  436. */
  437. toPromise(promiseCtor?: PromiseConstructorLike): Promise<T | undefined> {
  438. promiseCtor = getPromiseCtor(promiseCtor);
  439. return new promiseCtor((resolve, reject) => {
  440. let value: T | undefined;
  441. this.subscribe(
  442. (x: T) => (value = x),
  443. (err: any) => reject(err),
  444. () => resolve(value)
  445. );
  446. }) as Promise<T | undefined>;
  447. }
  448. }
  449. /**
  450. * Decides between a passed promise constructor from consuming code,
  451. * A default configured promise constructor, and the native promise
  452. * constructor and returns it. If nothing can be found, it will throw
  453. * an error.
  454. * @param promiseCtor The optional promise constructor to passed by consuming code
  455. */
  456. function getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {
  457. return promiseCtor ?? config.Promise ?? Promise;
  458. }
  459. function isObserver<T>(value: any): value is Observer<T> {
  460. return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
  461. }
  462. function isSubscriber<T>(value: any): value is Subscriber<T> {
  463. return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
  464. }