Every new change

This commit is contained in:
Luca Schwan
2020-03-25 11:05:34 +01:00
parent ff8491e75f
commit b4d041c5de
7164 changed files with 499221 additions and 135 deletions

49
node_modules/rxjs/src/internal/AsyncSubject.ts generated vendored Normal file
View File

@ -0,0 +1,49 @@
import { Subject } from './Subject';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
/**
* A variant of Subject that only emits a value when it completes. It will emit
* its latest value to all its observers on completion.
*
* @class AsyncSubject<T>
*/
export class AsyncSubject<T> extends Subject<T> {
private value: T = null;
private hasNext: boolean = false;
private hasCompleted: boolean = false;
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<any>): Subscription {
if (this.hasError) {
subscriber.error(this.thrownError);
return Subscription.EMPTY;
} else if (this.hasCompleted && this.hasNext) {
subscriber.next(this.value);
subscriber.complete();
return Subscription.EMPTY;
}
return super._subscribe(subscriber);
}
next(value: T): void {
if (!this.hasCompleted) {
this.value = value;
this.hasNext = true;
}
}
error(error: any): void {
if (!this.hasCompleted) {
super.error(error);
}
}
complete(): void {
this.hasCompleted = true;
if (this.hasNext) {
super.next(this.value);
}
super.complete();
}
}

45
node_modules/rxjs/src/internal/BehaviorSubject.ts generated vendored Normal file
View File

@ -0,0 +1,45 @@
import { Subject } from './Subject';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
import { SubscriptionLike } from './types';
import { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';
/**
* A variant of Subject that requires an initial value and emits its current
* value whenever it is subscribed to.
*
* @class BehaviorSubject<T>
*/
export class BehaviorSubject<T> extends Subject<T> {
constructor(private _value: T) {
super();
}
get value(): T {
return this.getValue();
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>): Subscription {
const subscription = super._subscribe(subscriber);
if (subscription && !(<SubscriptionLike>subscription).closed) {
subscriber.next(this._value);
}
return subscription;
}
getValue(): T {
if (this.hasError) {
throw this.thrownError;
} else if (this.closed) {
throw new ObjectUnsubscribedError();
} else {
return this._value;
}
}
next(value: T): void {
super.next(this._value = value);
}
}

29
node_modules/rxjs/src/internal/InnerSubscriber.ts generated vendored Normal file
View File

@ -0,0 +1,29 @@
import { Subscriber } from './Subscriber';
import { OuterSubscriber } from './OuterSubscriber';
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class InnerSubscriber<T, R> extends Subscriber<R> {
private index = 0;
constructor(private parent: OuterSubscriber<T, R>, public outerValue: T, public outerIndex: number) {
super();
}
protected _next(value: R): void {
this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
}
protected _error(error: any): void {
this.parent.notifyError(error, this);
this.unsubscribe();
}
protected _complete(): void {
this.parent.notifyComplete(this);
this.unsubscribe();
}
}

148
node_modules/rxjs/src/internal/Notification.ts generated vendored Normal file
View File

@ -0,0 +1,148 @@
import { PartialObserver } from './types';
import { Observable } from './Observable';
import { empty } from './observable/empty';
import { of } from './observable/of';
import { throwError } from './observable/throwError';
import { deprecate } from 'util';
// TODO: When this enum is removed, replace it with a type alias. See #4556.
/**
* @deprecated NotificationKind is deprecated as const enums are not compatible with isolated modules. Use a string literal instead.
*/
export enum NotificationKind {
NEXT = 'N',
ERROR = 'E',
COMPLETE = 'C',
}
/**
* Represents a push-based event or value that an {@link Observable} can emit.
* This class is particularly useful for operators that manage notifications,
* like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
* others. Besides wrapping the actual delivered value, it also annotates it
* with metadata of, for instance, what type of push message it is (`next`,
* `error`, or `complete`).
*
* @see {@link materialize}
* @see {@link dematerialize}
* @see {@link observeOn}
*
* @class Notification<T>
*/
export class Notification<T> {
hasValue: boolean;
constructor(public kind: 'N' | 'E' | 'C', public value?: T, public error?: any) {
this.hasValue = kind === 'N';
}
/**
* Delivers to the given `observer` the value wrapped by this Notification.
* @param {Observer} observer
* @return
*/
observe(observer: PartialObserver<T>): any {
switch (this.kind) {
case 'N':
return observer.next && observer.next(this.value);
case 'E':
return observer.error && observer.error(this.error);
case 'C':
return observer.complete && observer.complete();
}
}
/**
* Given some {@link Observer} callbacks, deliver the value represented by the
* current Notification to the correctly corresponding callback.
* @param {function(value: T): void} next An Observer `next` callback.
* @param {function(err: any): void} [error] An Observer `error` callback.
* @param {function(): void} [complete] An Observer `complete` callback.
* @return {any}
*/
do(next: (value: T) => void, error?: (err: any) => void, complete?: () => void): any {
const kind = this.kind;
switch (kind) {
case 'N':
return next && next(this.value);
case 'E':
return error && error(this.error);
case 'C':
return complete && complete();
}
}
/**
* Takes an Observer or its individual callback functions, and calls `observe`
* or `do` methods accordingly.
* @param {Observer|function(value: T): void} nextOrObserver An Observer or
* the `next` callback.
* @param {function(err: any): void} [error] An Observer `error` callback.
* @param {function(): void} [complete] An Observer `complete` callback.
* @return {any}
*/
accept(nextOrObserver: PartialObserver<T> | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {
if (nextOrObserver && typeof (<PartialObserver<T>>nextOrObserver).next === 'function') {
return this.observe(<PartialObserver<T>>nextOrObserver);
} else {
return this.do(<(value: T) => void>nextOrObserver, error, complete);
}
}
/**
* Returns a simple Observable that just delivers the notification represented
* by this Notification instance.
* @return {any}
*/
toObservable(): Observable<T> {
const kind = this.kind;
switch (kind) {
case 'N':
return of(this.value);
case 'E':
return throwError(this.error);
case 'C':
return empty();
}
throw new Error('unexpected notification kind value');
}
private static completeNotification: Notification<any> = new Notification('C');
private static undefinedValueNotification: Notification<any> = new Notification('N', undefined);
/**
* A shortcut to create a Notification instance of the type `next` from a
* given value.
* @param {T} value The `next` value.
* @return {Notification<T>} The "next" Notification representing the
* argument.
* @nocollapse
*/
static createNext<T>(value: T): Notification<T> {
if (typeof value !== 'undefined') {
return new Notification('N', value);
}
return Notification.undefinedValueNotification;
}
/**
* A shortcut to create a Notification instance of the type `error` from a
* given error.
* @param {any} [err] The `error` error.
* @return {Notification<T>} The "error" Notification representing the
* argument.
* @nocollapse
*/
static createError<T>(err?: any): Notification<T> {
return new Notification('E', undefined, err);
}
/**
* A shortcut to create a Notification instance of the type `complete`.
* @return {Notification<any>} The valueless "complete" Notification.
* @nocollapse
*/
static createComplete(): Notification<any> {
return Notification.completeNotification;
}
}

382
node_modules/rxjs/src/internal/Observable.ts generated vendored Normal file
View File

@ -0,0 +1,382 @@
import { Operator } from './Operator';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
import { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';
import { canReportError } from './util/canReportError';
import { toSubscriber } from './util/toSubscriber';
import { iif } from './observable/iif';
import { throwError } from './observable/throwError';
import { observable as Symbol_observable } from './symbol/observable';
import { pipeFromArray } from './util/pipe';
import { config } from './config';
/**
* A representation of any set of values over any amount of time. This is the most basic building block
* of RxJS.
*
* @class Observable<T>
*/
export class Observable<T> implements Subscribable<T> {
/** Internal implementation detail, do not use directly. */
public _isScalar: boolean = false;
/** @deprecated This is an internal implementation detail, do not use. */
source: Observable<any>;
/** @deprecated This is an internal implementation detail, do not use. */
operator: Operator<any, T>;
/**
* @constructor
* @param {Function} subscribe the function that is called when the Observable is
* initially subscribed to. This function is given a Subscriber, to which new values
* can be `next`ed, or an `error` method can be called to raise an error, or
* `complete` can be called to notify of a successful completion.
*/
constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
if (subscribe) {
this._subscribe = subscribe;
}
}
// HACK: Since TypeScript inherits static properties too, we have to
// fight against TypeScript here so Subject can have a different static create signature
/**
* Creates a new cold Observable by calling the Observable constructor
* @static true
* @owner Observable
* @method create
* @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
* @return {Observable} a new cold observable
* @nocollapse
* @deprecated use new Observable() instead
*/
static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {
return new Observable<T>(subscribe);
}
/**
* Creates a new Observable, with this Observable as the source, and the passed
* operator defined as the new observable's operator.
* @method lift
* @param {Operator} operator the operator defining the operation to take on the observable
* @return {Observable} a new observable with the Operator applied
*/
lift<R>(operator: Operator<T, R>): Observable<R> {
const observable = new Observable<R>();
observable.source = this;
observable.operator = operator;
return observable;
}
subscribe(observer?: PartialObserver<T>): Subscription;
/** @deprecated Use an observer instead of a complete callback */
subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;
/** @deprecated Use an observer instead of an error callback */
subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;
/** @deprecated Use an observer instead of a complete callback */
subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;
subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
/**
* Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
*
* <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
*
* `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
* might be for example a function that you passed to Observable's constructor, but most of the time it is
* a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means
* that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
* the thought.
*
* Apart from starting the execution of an Observable, this method allows you to listen for values
* that an Observable emits, as well as for when it completes or errors. You can achieve this in two
* of the following ways.
*
* The first way is creating an object that implements {@link Observer} interface. It should have methods
* defined by that interface, but note that it should be just a regular JavaScript object, which you can create
* yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
* not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
* that your object does not have to implement all methods. If you find yourself creating a method that doesn't
* do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will
* be left uncaught.
*
* The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
* This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent
* of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,
* if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
* since `subscribe` recognizes these functions by where they were placed in function call. When it comes
* to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
*
* Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.
* This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean
* up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
* provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
*
* Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
* It is an Observable itself that decides when these functions will be called. For example {@link of}
* by default emits all its values synchronously. Always check documentation for how given Observable
* will behave when subscribed and if its default behavior can be modified with a `scheduler`.
*
* ## Example
* ### Subscribe with an Observer
* ```ts
* import { of } from 'rxjs';
*
* const sumObserver = {
* sum: 0,
* next(value) {
* console.log('Adding: ' + value);
* this.sum = this.sum + value;
* },
* error() {
* // We actually could just remove this method,
* // since we do not really care about errors right now.
* },
* complete() {
* console.log('Sum equals: ' + this.sum);
* }
* };
*
* of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
* .subscribe(sumObserver);
*
* // Logs:
* // "Adding: 1"
* // "Adding: 2"
* // "Adding: 3"
* // "Sum equals: 6"
* ```
*
* ### Subscribe with functions
* ```ts
* import { of } from 'rxjs'
*
* let sum = 0;
*
* of(1, 2, 3).subscribe(
* value => {
* console.log('Adding: ' + value);
* sum = sum + value;
* },
* undefined,
* () => console.log('Sum equals: ' + sum)
* );
*
* // Logs:
* // "Adding: 1"
* // "Adding: 2"
* // "Adding: 3"
* // "Sum equals: 6"
* ```
*
* ### Cancel a subscription
* ```ts
* import { interval } from 'rxjs';
*
* const subscription = interval(1000).subscribe(
* num => console.log(num),
* undefined,
* () => {
* // Will not be called, even when cancelling subscription.
* console.log('completed!');
* }
* );
*
* setTimeout(() => {
* subscription.unsubscribe();
* console.log('unsubscribed!');
* }, 2500);
*
* // Logs:
* // 0 after 1s
* // 1 after 2s
* // "unsubscribed!" after 2.5s
* ```
*
* @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
* or the first of three possible handlers, which is the handler for each value emitted from the subscribed
* Observable.
* @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
* the error will be thrown as unhandled.
* @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
* @return {ISubscription} a subscription reference to the registered handlers
* @method subscribe
*/
subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),
error?: (error: any) => void,
complete?: () => void): Subscription {
const { operator } = this;
const sink = toSubscriber(observerOrNext, error, complete);
if (operator) {
sink.add(operator.call(sink, this.source));
} else {
sink.add(
this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
this._subscribe(sink) :
this._trySubscribe(sink)
);
}
if (config.useDeprecatedSynchronousErrorHandling) {
if (sink.syncErrorThrowable) {
sink.syncErrorThrowable = false;
if (sink.syncErrorThrown) {
throw sink.syncErrorValue;
}
}
}
return sink;
}
/** @deprecated This is an internal implementation detail, do not use. */
_trySubscribe(sink: Subscriber<T>): TeardownLogic {
try {
return this._subscribe(sink);
} catch (err) {
if (config.useDeprecatedSynchronousErrorHandling) {
sink.syncErrorThrown = true;
sink.syncErrorValue = err;
}
if (canReportError(sink)) {
sink.error(err);
} else {
console.warn(err);
}
}
}
/**
* @method forEach
* @param {Function} next a handler for each value emitted by the observable
* @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise
* @return {Promise} a promise that either resolves on observable completion or
* rejects with the handled error
*/
forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor<void>((resolve, reject) => {
// Must be declared in a separate statement to avoid a ReferenceError when
// accessing subscription below in the closure due to Temporal Dead Zone.
let subscription: Subscription;
subscription = this.subscribe((value) => {
try {
next(value);
} catch (err) {
reject(err);
if (subscription) {
subscription.unsubscribe();
}
}
}, reject, resolve);
}) as Promise<void>;
}
/** @internal This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<any>): TeardownLogic {
const { source } = this;
return source && source.subscribe(subscriber);
}
// `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in
// favor of iif and throwError functions.
/**
* @nocollapse
* @deprecated In favor of iif creation function: import { iif } from 'rxjs';
*/
static if: typeof iif;
/**
* @nocollapse
* @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';
*/
static throw: typeof throwError;
/**
* An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
* @method Symbol.observable
* @return {Observable} this instance of the observable
*/
[Symbol_observable]() {
return this;
}
/* tslint:disable:max-line-length */
pipe(): Observable<T>;
pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;
pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;
pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;
pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;
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>;
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>;
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>;
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>;
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>;
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<{}>;
/* tslint:enable:max-line-length */
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* ### Example
* ```ts
* import { interval } from 'rxjs';
* import { map, filter, scan } from 'rxjs/operators';
*
* interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
* ```
*/
pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {
if (operations.length === 0) {
return this as any;
}
return pipeFromArray(operations)(this);
}
/* tslint:disable:max-line-length */
toPromise<T>(this: Observable<T>): Promise<T>;
toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;
toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;
/* tslint:enable:max-line-length */
toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor((resolve, reject) => {
let value: any;
this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));
}) as Promise<T>;
}
}
/**
* Decides between a passed promise constructor from consuming code,
* A default configured promise constructor, and the native promise
* constructor and returns it. If nothing can be found, it will throw
* an error.
* @param promiseCtor The optional promise constructor to passed by consuming code
*/
function getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {
if (!promiseCtor) {
promiseCtor = config.Promise || Promise;
}
if (!promiseCtor) {
throw new Error('no Promise impl found');
}
return promiseCtor;
}

16
node_modules/rxjs/src/internal/Observer.ts generated vendored Normal file
View File

@ -0,0 +1,16 @@
import { Observer } from './types';
import { config } from './config';
import { hostReportError } from './util/hostReportError';
export const empty: Observer<any> = {
closed: true,
next(value: any): void { /* noop */},
error(err: any): void {
if (config.useDeprecatedSynchronousErrorHandling) {
throw err;
} else {
hostReportError(err);
}
},
complete(): void { /*noop*/ }
};

6
node_modules/rxjs/src/internal/Operator.ts generated vendored Normal file
View File

@ -0,0 +1,6 @@
import { Subscriber } from './Subscriber';
import { TeardownLogic } from './types';
export interface Operator<T, R> {
call(subscriber: Subscriber<R>, source: any): TeardownLogic;
}

23
node_modules/rxjs/src/internal/OuterSubscriber.ts generated vendored Normal file
View File

@ -0,0 +1,23 @@
import { Subscriber } from './Subscriber';
import { InnerSubscriber } from './InnerSubscriber';
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class OuterSubscriber<T, R> extends Subscriber<T> {
notifyNext(outerValue: T, innerValue: R,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
this.destination.next(innerValue);
}
notifyError(error: any, innerSub: InnerSubscriber<T, R>): void {
this.destination.error(error);
}
notifyComplete(innerSub: InnerSubscriber<T, R>): void {
this.destination.complete();
}
}

136
node_modules/rxjs/src/internal/ReplaySubject.ts generated vendored Normal file
View File

@ -0,0 +1,136 @@
import { Subject } from './Subject';
import { SchedulerLike } from './types';
import { queue } from './scheduler/queue';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
import { ObserveOnSubscriber } from './operators/observeOn';
import { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';
import { SubjectSubscription } from './SubjectSubscription';
/**
* A variant of Subject that "replays" or emits old values to new subscribers.
* It buffers a set number of values and will emit those values immediately to
* any new subscribers in addition to emitting new values to existing subscribers.
*
* @class ReplaySubject<T>
*/
export class ReplaySubject<T> extends Subject<T> {
private _events: (ReplayEvent<T> | T)[] = [];
private _bufferSize: number;
private _windowTime: number;
private _infiniteTimeWindow: boolean = false;
constructor(bufferSize: number = Number.POSITIVE_INFINITY,
windowTime: number = Number.POSITIVE_INFINITY,
private scheduler?: SchedulerLike) {
super();
this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
this._windowTime = windowTime < 1 ? 1 : windowTime;
if (windowTime === Number.POSITIVE_INFINITY) {
this._infiniteTimeWindow = true;
this.next = this.nextInfiniteTimeWindow;
} else {
this.next = this.nextTimeWindow;
}
}
private nextInfiniteTimeWindow(value: T): void {
const _events = this._events;
_events.push(value);
// Since this method is invoked in every next() call than the buffer
// can overgrow the max size only by one item
if (_events.length > this._bufferSize) {
_events.shift();
}
super.next(value);
}
private nextTimeWindow(value: T): void {
this._events.push(new ReplayEvent(this._getNow(), value));
this._trimBufferThenGetEvents();
super.next(value);
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>): Subscription {
// When `_infiniteTimeWindow === true` then the buffer is already trimmed
const _infiniteTimeWindow = this._infiniteTimeWindow;
const _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
const scheduler = this.scheduler;
const len = _events.length;
let subscription: Subscription;
if (this.closed) {
throw new ObjectUnsubscribedError();
} else if (this.isStopped || this.hasError) {
subscription = Subscription.EMPTY;
} else {
this.observers.push(subscriber);
subscription = new SubjectSubscription(this, subscriber);
}
if (scheduler) {
subscriber.add(subscriber = new ObserveOnSubscriber<T>(subscriber, scheduler));
}
if (_infiniteTimeWindow) {
for (let i = 0; i < len && !subscriber.closed; i++) {
subscriber.next(<T>_events[i]);
}
} else {
for (let i = 0; i < len && !subscriber.closed; i++) {
subscriber.next((<ReplayEvent<T>>_events[i]).value);
}
}
if (this.hasError) {
subscriber.error(this.thrownError);
} else if (this.isStopped) {
subscriber.complete();
}
return subscription;
}
_getNow(): number {
return (this.scheduler || queue).now();
}
private _trimBufferThenGetEvents(): ReplayEvent<T>[] {
const now = this._getNow();
const _bufferSize = this._bufferSize;
const _windowTime = this._windowTime;
const _events = <ReplayEvent<T>[]>this._events;
const eventsCount = _events.length;
let spliceCount = 0;
// Trim events that fall out of the time window.
// Start at the front of the list. Break early once
// we encounter an event that falls within the window.
while (spliceCount < eventsCount) {
if ((now - _events[spliceCount].time) < _windowTime) {
break;
}
spliceCount++;
}
if (eventsCount > _bufferSize) {
spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
}
if (spliceCount > 0) {
_events.splice(0, spliceCount);
}
return _events;
}
}
class ReplayEvent<T> {
constructor(public time: number, public value: T) {
}
}

228
node_modules/rxjs/src/internal/Rx.ts generated vendored Normal file
View File

@ -0,0 +1,228 @@
/* tslint:disable:no-unused-variable */
// Subject imported before Observable to bypass circular dependency issue since
// Subject extends Observable and Observable references Subject in it's
// definition
export {Subject, AnonymousSubject} from './Subject';
/* tslint:enable:no-unused-variable */
export {Observable} from './Observable';
export { config } from './config';
// statics
/* tslint:disable:no-use-before-declare */
import 'rxjs-compat/add/observable/bindCallback';
import 'rxjs-compat/add/observable/bindNodeCallback';
import 'rxjs-compat/add/observable/combineLatest';
import 'rxjs-compat/add/observable/concat';
import 'rxjs-compat/add/observable/defer';
import 'rxjs-compat/add/observable/empty';
import 'rxjs-compat/add/observable/forkJoin';
import 'rxjs-compat/add/observable/from';
import 'rxjs-compat/add/observable/fromEvent';
import 'rxjs-compat/add/observable/fromEventPattern';
import 'rxjs-compat/add/observable/fromPromise';
import 'rxjs-compat/add/observable/generate';
import 'rxjs-compat/add/observable/if';
import 'rxjs-compat/add/observable/interval';
import 'rxjs-compat/add/observable/merge';
import 'rxjs-compat/add/observable/race';
import 'rxjs-compat/add/observable/never';
import 'rxjs-compat/add/observable/of';
import 'rxjs-compat/add/observable/onErrorResumeNext';
import 'rxjs-compat/add/observable/pairs';
import 'rxjs-compat/add/observable/range';
import 'rxjs-compat/add/observable/using';
import 'rxjs-compat/add/observable/throw';
import 'rxjs-compat/add/observable/timer';
import 'rxjs-compat/add/observable/zip';
//dom
import 'rxjs-compat/add/observable/dom/ajax';
import 'rxjs-compat/add/observable/dom/webSocket';
//internal/operators
import 'rxjs-compat/add/operator/buffer';
import 'rxjs-compat/add/operator/bufferCount';
import 'rxjs-compat/add/operator/bufferTime';
import 'rxjs-compat/add/operator/bufferToggle';
import 'rxjs-compat/add/operator/bufferWhen';
import 'rxjs-compat/add/operator/catch';
import 'rxjs-compat/add/operator/combineAll';
import 'rxjs-compat/add/operator/combineLatest';
import 'rxjs-compat/add/operator/concat';
import 'rxjs-compat/add/operator/concatAll';
import 'rxjs-compat/add/operator/concatMap';
import 'rxjs-compat/add/operator/concatMapTo';
import 'rxjs-compat/add/operator/count';
import 'rxjs-compat/add/operator/dematerialize';
import 'rxjs-compat/add/operator/debounce';
import 'rxjs-compat/add/operator/debounceTime';
import 'rxjs-compat/add/operator/defaultIfEmpty';
import 'rxjs-compat/add/operator/delay';
import 'rxjs-compat/add/operator/delayWhen';
import 'rxjs-compat/add/operator/distinct';
import 'rxjs-compat/add/operator/distinctUntilChanged';
import 'rxjs-compat/add/operator/distinctUntilKeyChanged';
import 'rxjs-compat/add/operator/do';
import 'rxjs-compat/add/operator/exhaust';
import 'rxjs-compat/add/operator/exhaustMap';
import 'rxjs-compat/add/operator/expand';
import 'rxjs-compat/add/operator/elementAt';
import 'rxjs-compat/add/operator/filter';
import 'rxjs-compat/add/operator/finally';
import 'rxjs-compat/add/operator/find';
import 'rxjs-compat/add/operator/findIndex';
import 'rxjs-compat/add/operator/first';
import 'rxjs-compat/add/operator/groupBy';
import 'rxjs-compat/add/operator/ignoreElements';
import 'rxjs-compat/add/operator/isEmpty';
import 'rxjs-compat/add/operator/audit';
import 'rxjs-compat/add/operator/auditTime';
import 'rxjs-compat/add/operator/last';
import 'rxjs-compat/add/operator/let';
import 'rxjs-compat/add/operator/every';
import 'rxjs-compat/add/operator/map';
import 'rxjs-compat/add/operator/mapTo';
import 'rxjs-compat/add/operator/materialize';
import 'rxjs-compat/add/operator/max';
import 'rxjs-compat/add/operator/merge';
import 'rxjs-compat/add/operator/mergeAll';
import 'rxjs-compat/add/operator/mergeMap';
import 'rxjs-compat/add/operator/mergeMapTo';
import 'rxjs-compat/add/operator/mergeScan';
import 'rxjs-compat/add/operator/min';
import 'rxjs-compat/add/operator/multicast';
import 'rxjs-compat/add/operator/observeOn';
import 'rxjs-compat/add/operator/onErrorResumeNext';
import 'rxjs-compat/add/operator/pairwise';
import 'rxjs-compat/add/operator/partition';
import 'rxjs-compat/add/operator/pluck';
import 'rxjs-compat/add/operator/publish';
import 'rxjs-compat/add/operator/publishBehavior';
import 'rxjs-compat/add/operator/publishReplay';
import 'rxjs-compat/add/operator/publishLast';
import 'rxjs-compat/add/operator/race';
import 'rxjs-compat/add/operator/reduce';
import 'rxjs-compat/add/operator/repeat';
import 'rxjs-compat/add/operator/repeatWhen';
import 'rxjs-compat/add/operator/retry';
import 'rxjs-compat/add/operator/retryWhen';
import 'rxjs-compat/add/operator/sample';
import 'rxjs-compat/add/operator/sampleTime';
import 'rxjs-compat/add/operator/scan';
import 'rxjs-compat/add/operator/sequenceEqual';
import 'rxjs-compat/add/operator/share';
import 'rxjs-compat/add/operator/shareReplay';
import 'rxjs-compat/add/operator/single';
import 'rxjs-compat/add/operator/skip';
import 'rxjs-compat/add/operator/skipLast';
import 'rxjs-compat/add/operator/skipUntil';
import 'rxjs-compat/add/operator/skipWhile';
import 'rxjs-compat/add/operator/startWith';
import 'rxjs-compat/add/operator/subscribeOn';
import 'rxjs-compat/add/operator/switch';
import 'rxjs-compat/add/operator/switchMap';
import 'rxjs-compat/add/operator/switchMapTo';
import 'rxjs-compat/add/operator/take';
import 'rxjs-compat/add/operator/takeLast';
import 'rxjs-compat/add/operator/takeUntil';
import 'rxjs-compat/add/operator/takeWhile';
import 'rxjs-compat/add/operator/throttle';
import 'rxjs-compat/add/operator/throttleTime';
import 'rxjs-compat/add/operator/timeInterval';
import 'rxjs-compat/add/operator/timeout';
import 'rxjs-compat/add/operator/timeoutWith';
import 'rxjs-compat/add/operator/timestamp';
import 'rxjs-compat/add/operator/toArray';
import 'rxjs-compat/add/operator/toPromise';
import 'rxjs-compat/add/operator/window';
import 'rxjs-compat/add/operator/windowCount';
import 'rxjs-compat/add/operator/windowTime';
import 'rxjs-compat/add/operator/windowToggle';
import 'rxjs-compat/add/operator/windowWhen';
import 'rxjs-compat/add/operator/withLatestFrom';
import 'rxjs-compat/add/operator/zip';
import 'rxjs-compat/add/operator/zipAll';
/* tslint:disable:no-unused-variable */
export {Operator} from './Operator';
export {Observer} from './types';
export {Subscription} from './Subscription';
export {Subscriber} from './Subscriber';
export {AsyncSubject} from './AsyncSubject';
export {ReplaySubject} from './ReplaySubject';
export {BehaviorSubject} from './BehaviorSubject';
export {ConnectableObservable} from './observable/ConnectableObservable';
export {Notification, NotificationKind} from './Notification';
export {EmptyError} from './util/EmptyError';
export {ArgumentOutOfRangeError} from './util/ArgumentOutOfRangeError';
export {ObjectUnsubscribedError} from './util/ObjectUnsubscribedError';
export {TimeoutError} from './util/TimeoutError';
export {UnsubscriptionError} from './util/UnsubscriptionError';
export {TimeInterval} from './operators/timeInterval';
export {Timestamp} from './operators/timestamp';
export {TestScheduler} from './testing/TestScheduler';
export {VirtualTimeScheduler} from './scheduler/VirtualTimeScheduler';
export {AjaxRequest, AjaxResponse, AjaxError, AjaxTimeoutError} from './observable/dom/AjaxObservable';
export { pipe } from './util/pipe';
import { asap } from './scheduler/asap';
import { async } from './scheduler/async';
import { queue } from './scheduler/queue';
import { animationFrame } from './scheduler/animationFrame';
import { AsapScheduler } from './scheduler/AsapScheduler';
import { AsyncScheduler } from './scheduler/AsyncScheduler';
import { QueueScheduler } from './scheduler/QueueScheduler';
import { AnimationFrameScheduler } from './scheduler/AnimationFrameScheduler';
import { rxSubscriber } from './symbol/rxSubscriber';
import { iterator } from './symbol/iterator';
import { observable } from './symbol/observable';
import * as _operators from './operators/index';
export const operators = _operators;
/* tslint:enable:no-unused-variable */
/**
* @typedef {Object} Rx.Scheduler
* @property {SchedulerLike} asap Schedules on the micro task queue, which is the same
* queue used for promises. Basically after the current job, but before the next job.
* Use this for asynchronous conversions.
* @property {SchedulerLike} queue Schedules on a queue in the current event frame
* (trampoline scheduler). Use this for iteration operations.
* @property {SchedulerLike} animationFrame Schedules work with `requestAnimationFrame`.
* Use this for synchronizing with the platform's painting.
* @property {SchedulerLike} async Schedules work with `setInterval`. Use this for
* time-based operations.
*/
let Scheduler = {
asap,
queue,
animationFrame,
async
};
/**
* @typedef {Object} Rx.Symbol
* @property {Symbol|string} rxSubscriber A symbol to use as a property name to
* retrieve an "Rx safe" Observer from an object. "Rx safety" can be defined as
* an object that has all of the traits of an Rx Subscriber, including the
* ability to add and remove subscriptions to the subscription chain and
* guarantees involving event triggering (can't "next" after unsubscription,
* etc).
* @property {Symbol|string} observable A symbol to use as a property name to
* retrieve an Observable as defined by the [ECMAScript "Observable" spec](https://github.com/zenparsing/es-observable).
* @property {Symbol|string} iterator The ES6 symbol to use as a property name
* to retrieve an iterator from an object.
*/
let Symbol = {
rxSubscriber,
observable,
iterator
};
export {
Scheduler,
Symbol
};

68
node_modules/rxjs/src/internal/Scheduler.ts generated vendored Normal file
View File

@ -0,0 +1,68 @@
import { Action } from './scheduler/Action';
import { Subscription } from './Subscription';
import { SchedulerLike, SchedulerAction } from './types';
/**
* An execution context and a data structure to order tasks and schedule their
* execution. Provides a notion of (potentially virtual) time, through the
* `now()` getter method.
*
* Each unit of work in a Scheduler is called an `Action`.
*
* ```ts
* class Scheduler {
* now(): number;
* schedule(work, delay?, state?): Subscription;
* }
* ```
*
* @class Scheduler
* @deprecated Scheduler is an internal implementation detail of RxJS, and
* should not be used directly. Rather, create your own class and implement
* {@link SchedulerLike}
*/
export class Scheduler implements SchedulerLike {
/**
* Note: the extra arrow function wrapper is to make testing by overriding
* Date.now easier.
* @nocollapse
*/
public static now: () => number = () => Date.now();
constructor(private SchedulerAction: typeof Action,
now: () => number = Scheduler.now) {
this.now = now;
}
/**
* A getter method that returns a number representing the current time
* (at the time this function was called) according to the scheduler's own
* internal clock.
* @return {number} A number that represents the current time. May or may not
* have a relation to wall-clock time. May or may not refer to a time unit
* (e.g. milliseconds).
*/
public now: () => number;
/**
* Schedules a function, `work`, for execution. May happen at some point in
* the future, according to the `delay` parameter, if specified. May be passed
* some context object, `state`, which will be passed to the `work` function.
*
* The given arguments will be processed an stored as an Action object in a
* queue of actions.
*
* @param {function(state: ?T): ?Subscription} work A function representing a
* task, or some unit of work to be executed by the Scheduler.
* @param {number} [delay] Time to wait before executing the work, where the
* time unit is implicit and defined by the Scheduler itself.
* @param {T} [state] Some contextual data that the `work` function uses when
* called by the Scheduler.
* @return {Subscription} A subscription in order to be able to unsubscribe
* the scheduled work.
*/
public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {
return new this.SchedulerAction<T>(this, work).schedule(state, delay);
}
}

188
node_modules/rxjs/src/internal/Subject.ts generated vendored Normal file
View File

@ -0,0 +1,188 @@
import { Operator } from './Operator';
import { Observable } from './Observable';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
import { Observer, SubscriptionLike, TeardownLogic } from './types';
import { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';
import { SubjectSubscription } from './SubjectSubscription';
import { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';
/**
* @class SubjectSubscriber<T>
*/
export class SubjectSubscriber<T> extends Subscriber<T> {
constructor(protected destination: Subject<T>) {
super(destination);
}
}
/**
* A Subject is a special type of Observable that allows values to be
* multicasted to many Observers. Subjects are like EventEmitters.
*
* Every Subject is an Observable and an Observer. You can subscribe to a
* Subject, and you can call next to feed values as well as error and complete.
*
* @class Subject<T>
*/
export class Subject<T> extends Observable<T> implements SubscriptionLike {
[rxSubscriberSymbol]() {
return new SubjectSubscriber(this);
}
observers: Observer<T>[] = [];
closed = false;
isStopped = false;
hasError = false;
thrownError: any = null;
constructor() {
super();
}
/**@nocollapse
* @deprecated use new Subject() instead
*/
static create: Function = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {
return new AnonymousSubject<T>(destination, source);
}
lift<R>(operator: Operator<T, R>): Observable<R> {
const subject = new AnonymousSubject(this, this);
subject.operator = <any>operator;
return <any>subject;
}
next(value?: T) {
if (this.closed) {
throw new ObjectUnsubscribedError();
}
if (!this.isStopped) {
const { observers } = this;
const len = observers.length;
const copy = observers.slice();
for (let i = 0; i < len; i++) {
copy[i].next(value);
}
}
}
error(err: any) {
if (this.closed) {
throw new ObjectUnsubscribedError();
}
this.hasError = true;
this.thrownError = err;
this.isStopped = true;
const { observers } = this;
const len = observers.length;
const copy = observers.slice();
for (let i = 0; i < len; i++) {
copy[i].error(err);
}
this.observers.length = 0;
}
complete() {
if (this.closed) {
throw new ObjectUnsubscribedError();
}
this.isStopped = true;
const { observers } = this;
const len = observers.length;
const copy = observers.slice();
for (let i = 0; i < len; i++) {
copy[i].complete();
}
this.observers.length = 0;
}
unsubscribe() {
this.isStopped = true;
this.closed = true;
this.observers = null;
}
/** @deprecated This is an internal implementation detail, do not use. */
_trySubscribe(subscriber: Subscriber<T>): TeardownLogic {
if (this.closed) {
throw new ObjectUnsubscribedError();
} else {
return super._trySubscribe(subscriber);
}
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>): Subscription {
if (this.closed) {
throw new ObjectUnsubscribedError();
} else if (this.hasError) {
subscriber.error(this.thrownError);
return Subscription.EMPTY;
} else if (this.isStopped) {
subscriber.complete();
return Subscription.EMPTY;
} else {
this.observers.push(subscriber);
return new SubjectSubscription(this, subscriber);
}
}
/**
* Creates a new Observable with this Subject as the source. You can do this
* to create customize Observer-side logic of the Subject and conceal it from
* code that uses the Observable.
* @return {Observable} Observable that the Subject casts to
*/
asObservable(): Observable<T> {
const observable = new Observable<T>();
(<any>observable).source = this;
return observable;
}
}
/**
* @class AnonymousSubject<T>
*/
export class AnonymousSubject<T> extends Subject<T> {
constructor(protected destination?: Observer<T>, source?: Observable<T>) {
super();
this.source = source;
}
next(value: T) {
const { destination } = this;
if (destination && destination.next) {
destination.next(value);
}
}
error(err: any) {
const { destination } = this;
if (destination && destination.error) {
this.destination.error(err);
}
}
complete() {
const { destination } = this;
if (destination && destination.complete) {
this.destination.complete();
}
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>): Subscription {
const { source } = this;
if (source) {
return this.source.subscribe(subscriber);
} else {
return Subscription.EMPTY;
}
}
}

39
node_modules/rxjs/src/internal/SubjectSubscription.ts generated vendored Normal file
View File

@ -0,0 +1,39 @@
import { Subject } from './Subject';
import { Observer } from './types';
import { Subscription } from './Subscription';
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class SubjectSubscription<T> extends Subscription {
closed: boolean = false;
constructor(public subject: Subject<T>, public subscriber: Observer<T>) {
super();
}
unsubscribe() {
if (this.closed) {
return;
}
this.closed = true;
const subject = this.subject;
const observers = subject.observers;
this.subject = null;
if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
return;
}
const subscriberIndex = observers.indexOf(this.subscriber);
if (subscriberIndex !== -1) {
observers.splice(subscriberIndex, 1);
}
}
}

302
node_modules/rxjs/src/internal/Subscriber.ts generated vendored Normal file
View File

@ -0,0 +1,302 @@
import { isFunction } from './util/isFunction';
import { empty as emptyObserver } from './Observer';
import { Observer, PartialObserver, TeardownLogic } from './types';
import { Subscription } from './Subscription';
import { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';
import { config } from './config';
import { hostReportError } from './util/hostReportError';
/**
* Implements the {@link Observer} interface and extends the
* {@link Subscription} class. While the {@link Observer} is the public API for
* consuming the values of an {@link Observable}, all Observers get converted to
* a Subscriber, in order to provide Subscription-like capabilities such as
* `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
* implementing operators, but it is rarely used as a public API.
*
* @class Subscriber<T>
*/
export class Subscriber<T> extends Subscription implements Observer<T> {
[rxSubscriberSymbol]() { return this; }
/**
* A static factory for a Subscriber, given a (potentially partial) definition
* of an Observer.
* @param {function(x: ?T): void} [next] The `next` callback of an Observer.
* @param {function(e: ?any): void} [error] The `error` callback of an
* Observer.
* @param {function(): void} [complete] The `complete` callback of an
* Observer.
* @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
* Observer represented by the given arguments.
* @nocollapse
*/
static create<T>(next?: (x?: T) => void,
error?: (e?: any) => void,
complete?: () => void): Subscriber<T> {
const subscriber = new Subscriber(next, error, complete);
subscriber.syncErrorThrowable = false;
return subscriber;
}
/** @internal */ syncErrorValue: any = null;
/** @internal */ syncErrorThrown: boolean = false;
/** @internal */ syncErrorThrowable: boolean = false;
protected isStopped: boolean = false;
protected destination: PartialObserver<any> | Subscriber<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)
/**
* @param {Observer|function(value: T): void} [destinationOrNext] A partially
* defined Observer or a `next` callback function.
* @param {function(e: ?any): void} [error] The `error` callback of an
* Observer.
* @param {function(): void} [complete] The `complete` callback of an
* Observer.
*/
constructor(destinationOrNext?: PartialObserver<any> | ((value: T) => void),
error?: (e?: any) => void,
complete?: () => void) {
super();
switch (arguments.length) {
case 0:
this.destination = emptyObserver;
break;
case 1:
if (!destinationOrNext) {
this.destination = emptyObserver;
break;
}
if (typeof destinationOrNext === 'object') {
if (destinationOrNext instanceof Subscriber) {
this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
this.destination = destinationOrNext;
destinationOrNext.add(this);
} else {
this.syncErrorThrowable = true;
this.destination = new SafeSubscriber<T>(this, <PartialObserver<any>> destinationOrNext);
}
break;
}
default:
this.syncErrorThrowable = true;
this.destination = new SafeSubscriber<T>(this, <((value: T) => void)> destinationOrNext, error, complete);
break;
}
}
/**
* The {@link Observer} callback to receive notifications of type `next` from
* the Observable, with a value. The Observable may call this method 0 or more
* times.
* @param {T} [value] The `next` value.
* @return {void}
*/
next(value?: T): void {
if (!this.isStopped) {
this._next(value);
}
}
/**
* The {@link Observer} callback to receive notifications of type `error` from
* the Observable, with an attached `Error`. Notifies the Observer that
* the Observable has experienced an error condition.
* @param {any} [err] The `error` exception.
* @return {void}
*/
error(err?: any): void {
if (!this.isStopped) {
this.isStopped = true;
this._error(err);
}
}
/**
* The {@link Observer} callback to receive a valueless notification of type
* `complete` from the Observable. Notifies the Observer that the Observable
* has finished sending push-based notifications.
* @return {void}
*/
complete(): void {
if (!this.isStopped) {
this.isStopped = true;
this._complete();
}
}
unsubscribe(): void {
if (this.closed) {
return;
}
this.isStopped = true;
super.unsubscribe();
}
protected _next(value: T): void {
this.destination.next(value);
}
protected _error(err: any): void {
this.destination.error(err);
this.unsubscribe();
}
protected _complete(): void {
this.destination.complete();
this.unsubscribe();
}
/** @deprecated This is an internal implementation detail, do not use. */
_unsubscribeAndRecycle(): Subscriber<T> {
const { _parentOrParents } = this;
this._parentOrParents = null;
this.unsubscribe();
this.closed = false;
this.isStopped = false;
this._parentOrParents = _parentOrParents;
return this;
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class SafeSubscriber<T> extends Subscriber<T> {
private _context: any;
constructor(private _parentSubscriber: Subscriber<T>,
observerOrNext?: PartialObserver<T> | ((value: T) => void),
error?: (e?: any) => void,
complete?: () => void) {
super();
let next: ((value: T) => void);
let context: any = this;
if (isFunction(observerOrNext)) {
next = (<((value: T) => void)> observerOrNext);
} else if (observerOrNext) {
next = (<PartialObserver<T>> observerOrNext).next;
error = (<PartialObserver<T>> observerOrNext).error;
complete = (<PartialObserver<T>> observerOrNext).complete;
if (observerOrNext !== emptyObserver) {
context = Object.create(observerOrNext);
if (isFunction(context.unsubscribe)) {
this.add(<() => void> context.unsubscribe.bind(context));
}
context.unsubscribe = this.unsubscribe.bind(this);
}
}
this._context = context;
this._next = next;
this._error = error;
this._complete = complete;
}
next(value?: T): void {
if (!this.isStopped && this._next) {
const { _parentSubscriber } = this;
if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(this._next, value);
} else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
this.unsubscribe();
}
}
}
error(err?: any): void {
if (!this.isStopped) {
const { _parentSubscriber } = this;
const { useDeprecatedSynchronousErrorHandling } = config;
if (this._error) {
if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(this._error, err);
this.unsubscribe();
} else {
this.__tryOrSetError(_parentSubscriber, this._error, err);
this.unsubscribe();
}
} else if (!_parentSubscriber.syncErrorThrowable) {
this.unsubscribe();
if (useDeprecatedSynchronousErrorHandling) {
throw err;
}
hostReportError(err);
} else {
if (useDeprecatedSynchronousErrorHandling) {
_parentSubscriber.syncErrorValue = err;
_parentSubscriber.syncErrorThrown = true;
} else {
hostReportError(err);
}
this.unsubscribe();
}
}
}
complete(): void {
if (!this.isStopped) {
const { _parentSubscriber } = this;
if (this._complete) {
const wrappedComplete = () => this._complete.call(this._context);
if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
this.__tryOrUnsub(wrappedComplete);
this.unsubscribe();
} else {
this.__tryOrSetError(_parentSubscriber, wrappedComplete);
this.unsubscribe();
}
} else {
this.unsubscribe();
}
}
}
private __tryOrUnsub(fn: Function, value?: any): void {
try {
fn.call(this._context, value);
} catch (err) {
this.unsubscribe();
if (config.useDeprecatedSynchronousErrorHandling) {
throw err;
} else {
hostReportError(err);
}
}
}
private __tryOrSetError(parent: Subscriber<T>, fn: Function, value?: any): boolean {
if (!config.useDeprecatedSynchronousErrorHandling) {
throw new Error('bad call');
}
try {
fn.call(this._context, value);
} catch (err) {
if (config.useDeprecatedSynchronousErrorHandling) {
parent.syncErrorValue = err;
parent.syncErrorThrown = true;
return true;
} else {
hostReportError(err);
return true;
}
}
return false;
}
/** @internal This is an internal implementation detail, do not use. */
_unsubscribe(): void {
const { _parentSubscriber } = this;
this._context = null;
this._parentSubscriber = null;
_parentSubscriber.unsubscribe();
}
}

211
node_modules/rxjs/src/internal/Subscription.ts generated vendored Normal file
View File

@ -0,0 +1,211 @@
import { isArray } from './util/isArray';
import { isObject } from './util/isObject';
import { isFunction } from './util/isFunction';
import { UnsubscriptionError } from './util/UnsubscriptionError';
import { SubscriptionLike, TeardownLogic } from './types';
/**
* Represents a disposable resource, such as the execution of an Observable. A
* Subscription has one important method, `unsubscribe`, that takes no argument
* and just disposes the resource held by the subscription.
*
* Additionally, subscriptions may be grouped together through the `add()`
* method, which will attach a child Subscription to the current Subscription.
* When a Subscription is unsubscribed, all its children (and its grandchildren)
* will be unsubscribed as well.
*
* @class Subscription
*/
export class Subscription implements SubscriptionLike {
/** @nocollapse */
public static EMPTY: Subscription = (function(empty: any) {
empty.closed = true;
return empty;
}(new Subscription()));
/**
* A flag to indicate whether this Subscription has already been unsubscribed.
* @type {boolean}
*/
public closed: boolean = false;
/** @internal */
protected _parentOrParents: Subscription | Subscription[] = null;
/** @internal */
private _subscriptions: SubscriptionLike[] = null;
/**
* @param {function(): void} [unsubscribe] A function describing how to
* perform the disposal of resources when the `unsubscribe` method is called.
*/
constructor(unsubscribe?: () => void) {
if (unsubscribe) {
(<any> this)._unsubscribe = unsubscribe;
}
}
/**
* Disposes the resources held by the subscription. May, for instance, cancel
* an ongoing Observable execution or cancel any other type of work that
* started when the Subscription was created.
* @return {void}
*/
unsubscribe(): void {
let errors: any[];
if (this.closed) {
return;
}
let { _parentOrParents, _unsubscribe, _subscriptions } = (<any> this);
this.closed = true;
this._parentOrParents = null;
// null out _subscriptions first so any child subscriptions that attempt
// to remove themselves from this subscription will noop
this._subscriptions = null;
if (_parentOrParents instanceof Subscription) {
_parentOrParents.remove(this);
} else if (_parentOrParents !== null) {
for (let index = 0; index < _parentOrParents.length; ++index) {
const parent = _parentOrParents[index];
parent.remove(this);
}
}
if (isFunction(_unsubscribe)) {
try {
_unsubscribe.call(this);
} catch (e) {
errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
}
}
if (isArray(_subscriptions)) {
let index = -1;
let len = _subscriptions.length;
while (++index < len) {
const sub = _subscriptions[index];
if (isObject(sub)) {
try {
sub.unsubscribe();
} catch (e) {
errors = errors || [];
if (e instanceof UnsubscriptionError) {
errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
} else {
errors.push(e);
}
}
}
}
}
if (errors) {
throw new UnsubscriptionError(errors);
}
}
/**
* Adds a tear down to be called during the unsubscribe() of this
* Subscription. Can also be used to add a child subscription.
*
* If the tear down being added is a subscription that is already
* unsubscribed, is the same reference `add` is being called on, or is
* `Subscription.EMPTY`, it will not be added.
*
* If this subscription is already in an `closed` state, the passed
* tear down logic will be executed immediately.
*
* When a parent subscription is unsubscribed, any child subscriptions that were added to it are also unsubscribed.
*
* @param {TeardownLogic} teardown The additional logic to execute on
* teardown.
* @return {Subscription} Returns the Subscription used or created to be
* added to the inner subscriptions list. This Subscription can be used with
* `remove()` to remove the passed teardown logic from the inner subscriptions
* list.
*/
add(teardown: TeardownLogic): Subscription {
let subscription = (<Subscription>teardown);
if (!(<any>teardown)) {
return Subscription.EMPTY;
}
switch (typeof teardown) {
case 'function':
subscription = new Subscription(<(() => void)>teardown);
case 'object':
if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
// This also covers the case where `subscription` is `Subscription.EMPTY`, which is always in `closed` state.
return subscription;
} else if (this.closed) {
subscription.unsubscribe();
return subscription;
} else if (!(subscription instanceof Subscription)) {
const tmp = subscription;
subscription = new Subscription();
subscription._subscriptions = [tmp];
}
break;
default: {
throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
}
}
// Add `this` as parent of `subscription` if that's not already the case.
let { _parentOrParents } = subscription;
if (_parentOrParents === null) {
// If we don't have a parent, then set `subscription._parents` to
// the `this`, which is the common case that we optimize for.
subscription._parentOrParents = this;
} else if (_parentOrParents instanceof Subscription) {
if (_parentOrParents === this) {
// The `subscription` already has `this` as a parent.
return subscription;
}
// If there's already one parent, but not multiple, allocate an
// Array to store the rest of the parent Subscriptions.
subscription._parentOrParents = [_parentOrParents, this];
} else if (_parentOrParents.indexOf(this) === -1) {
// Only add `this` to the _parentOrParents list if it's not already there.
_parentOrParents.push(this);
} else {
// The `subscription` already has `this` as a parent.
return subscription;
}
// Optimize for the common case when adding the first subscription.
const subscriptions = this._subscriptions;
if (subscriptions === null) {
this._subscriptions = [subscription];
} else {
subscriptions.push(subscription);
}
return subscription;
}
/**
* Removes a Subscription from the internal list of subscriptions that will
* unsubscribe during the unsubscribe process of this Subscription.
* @param {Subscription} subscription The subscription to remove.
* @return {void}
*/
remove(subscription: Subscription): void {
const subscriptions = this._subscriptions;
if (subscriptions) {
const subscriptionIndex = subscriptions.indexOf(subscription);
if (subscriptionIndex !== -1) {
subscriptions.splice(subscriptionIndex, 1);
}
}
}
}
function flattenUnsubscriptionErrors(errors: any[]) {
return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);
}

35
node_modules/rxjs/src/internal/config.ts generated vendored Normal file
View File

@ -0,0 +1,35 @@
let _enable_super_gross_mode_that_will_cause_bad_things = false;
/**
* The global configuration object for RxJS, used to configure things
* like what Promise contructor should used to create Promises
*/
export const config = {
/**
* The promise constructor used by default for methods such as
* {@link toPromise} and {@link forEach}
*/
Promise: undefined as PromiseConstructorLike,
/**
* If true, turns on synchronous error rethrowing, which is a deprecated behavior
* in v6 and higher. This behavior enables bad patterns like wrapping a subscribe
* call in a try/catch block. It also enables producer interference, a nasty bug
* where a multicast can be broken for all observers by a downstream consumer with
* an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BY TIME
* FOR MIGRATION REASONS.
*/
set useDeprecatedSynchronousErrorHandling(value: boolean) {
if (value) {
const error = new Error();
console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
} else if (_enable_super_gross_mode_that_will_cause_bad_things) {
console.log('RxJS: Back to a better error behavior. Thank you. <3');
}
_enable_super_gross_mode_that_will_cause_bad_things = value;
},
get useDeprecatedSynchronousErrorHandling() {
return _enable_super_gross_mode_that_will_cause_bad_things;
},
};

View File

@ -0,0 +1,182 @@
import { Subject, SubjectSubscriber } from '../Subject';
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { TeardownLogic } from '../types';
import { refCount as higherOrderRefCount } from '../operators/refCount';
/**
* @class ConnectableObservable<T>
*/
export class ConnectableObservable<T> extends Observable<T> {
protected _subject: Subject<T>;
protected _refCount: number = 0;
protected _connection: Subscription;
/** @internal */
_isComplete = false;
constructor(public source: Observable<T>,
protected subjectFactory: () => Subject<T>) {
super();
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>) {
return this.getSubject().subscribe(subscriber);
}
protected getSubject(): Subject<T> {
const subject = this._subject;
if (!subject || subject.isStopped) {
this._subject = this.subjectFactory();
}
return this._subject;
}
connect(): Subscription {
let connection = this._connection;
if (!connection) {
this._isComplete = false;
connection = this._connection = new Subscription();
connection.add(this.source
.subscribe(new ConnectableSubscriber(this.getSubject(), this)));
if (connection.closed) {
this._connection = null;
connection = Subscription.EMPTY;
}
}
return connection;
}
refCount(): Observable<T> {
return higherOrderRefCount()(this) as Observable<T>;
}
}
export const connectableObservableDescriptor: PropertyDescriptorMap = (() => {
const connectableProto = <any>ConnectableObservable.prototype;
return {
operator: { value: null as null },
_refCount: { value: 0, writable: true },
_subject: { value: null as null, writable: true },
_connection: { value: null as null, writable: true },
_subscribe: { value: connectableProto._subscribe },
_isComplete: { value: connectableProto._isComplete, writable: true },
getSubject: { value: connectableProto.getSubject },
connect: { value: connectableProto.connect },
refCount: { value: connectableProto.refCount }
};
})();
class ConnectableSubscriber<T> extends SubjectSubscriber<T> {
constructor(destination: Subject<T>,
private connectable: ConnectableObservable<T>) {
super(destination);
}
protected _error(err: any): void {
this._unsubscribe();
super._error(err);
}
protected _complete(): void {
this.connectable._isComplete = true;
this._unsubscribe();
super._complete();
}
protected _unsubscribe() {
const connectable = <any>this.connectable;
if (connectable) {
this.connectable = null;
const connection = connectable._connection;
connectable._refCount = 0;
connectable._subject = null;
connectable._connection = null;
if (connection) {
connection.unsubscribe();
}
}
}
}
class RefCountOperator<T> implements Operator<T, T> {
constructor(private connectable: ConnectableObservable<T>) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
const { connectable } = this;
(<any> connectable)._refCount++;
const refCounter = new RefCountSubscriber(subscriber, connectable);
const subscription = source.subscribe(refCounter);
if (!refCounter.closed) {
(<any> refCounter).connection = connectable.connect();
}
return subscription;
}
}
class RefCountSubscriber<T> extends Subscriber<T> {
private connection: Subscription;
constructor(destination: Subscriber<T>,
private connectable: ConnectableObservable<T>) {
super(destination);
}
protected _unsubscribe() {
const { connectable } = this;
if (!connectable) {
this.connection = null;
return;
}
this.connectable = null;
const refCount = (<any> connectable)._refCount;
if (refCount <= 0) {
this.connection = null;
return;
}
(<any> connectable)._refCount = refCount - 1;
if (refCount > 1) {
this.connection = null;
return;
}
///
// Compare the local RefCountSubscriber's connection Subscription to the
// connection Subscription on the shared ConnectableObservable. In cases
// where the ConnectableObservable source synchronously emits values, and
// the RefCountSubscriber's downstream Observers synchronously unsubscribe,
// execution continues to here before the RefCountOperator has a chance to
// supply the RefCountSubscriber with the shared connection Subscription.
// For example:
// ```
// range(0, 10).pipe(
// publish(),
// refCount(),
// take(5),
// ).subscribe();
// ```
// In order to account for this case, RefCountSubscriber should only dispose
// the ConnectableObservable's shared connection Subscription if the
// connection Subscription exists, *and* either:
// a. RefCountSubscriber doesn't have a reference to the shared connection
// Subscription yet, or,
// b. RefCountSubscriber's connection Subscription reference is identical
// to the shared connection Subscription
///
const { connection } = this;
const sharedConnection = (<any> connectable)._connection;
this.connection = null;
if (sharedConnection && (!connection || sharedConnection === connection)) {
sharedConnection.unsubscribe();
}
}
}

View File

@ -0,0 +1,52 @@
import { SchedulerLike, SchedulerAction } from '../types';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { Observable } from '../Observable';
import { asap } from '../scheduler/asap';
import { isNumeric } from '../util/isNumeric';
export interface DispatchArg<T> {
source: Observable<T>;
subscriber: Subscriber<T>;
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
export class SubscribeOnObservable<T> extends Observable<T> {
/** @nocollapse */
static create<T>(source: Observable<T>, delay: number = 0, scheduler: SchedulerLike = asap): Observable<T> {
return new SubscribeOnObservable(source, delay, scheduler);
}
/** @nocollapse */
static dispatch<T>(this: SchedulerAction<T>, arg: DispatchArg<T>): Subscription {
const { source, subscriber } = arg;
return this.add(source.subscribe(subscriber));
}
constructor(public source: Observable<T>,
private delayTime: number = 0,
private scheduler: SchedulerLike = asap) {
super();
if (!isNumeric(delayTime) || delayTime < 0) {
this.delayTime = 0;
}
if (!scheduler || typeof scheduler.schedule !== 'function') {
this.scheduler = asap;
}
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>) {
const delay = this.delayTime;
const source = this.source;
const scheduler = this.scheduler;
return scheduler.schedule<DispatchArg<any>>(SubscribeOnObservable.dispatch, delay, {
source, subscriber
});
}
}

View File

@ -0,0 +1,290 @@
import { SchedulerLike, SchedulerAction } from '../types';
import { Observable } from '../Observable';
import { AsyncSubject } from '../AsyncSubject';
import { Subscriber } from '../Subscriber';
import { map } from '../operators/map';
import { canReportError } from '../util/canReportError';
import { isArray } from '../util/isArray';
import { isScheduler } from '../util/isScheduler';
// tslint:disable:max-line-length
/** @deprecated resultSelector is no longer supported, use a mapping function. */
export function bindCallback(callbackFunc: Function, resultSelector: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable<any>;
export function bindCallback<R1, R2, R3, R4>(callbackFunc: (callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): () => Observable<any[]>;
export function bindCallback<R1, R2, R3>(callbackFunc: (callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2, R3]>;
export function bindCallback<R1, R2>(callbackFunc: (callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2]>;
export function bindCallback<R1>(callbackFunc: (callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): () => Observable<R1>;
export function bindCallback(callbackFunc: (callback: () => any) => any, scheduler?: SchedulerLike): () => Observable<void>;
export function bindCallback<A1, R1, R2, R3, R4>(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<any[]>;
export function bindCallback<A1, R1, R2, R3>(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2, R3]>;
export function bindCallback<A1, R1, R2>(callbackFunc: (arg1: A1, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2]>;
export function bindCallback<A1, R1>(callbackFunc: (arg1: A1, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<R1>;
export function bindCallback<A1>(callbackFunc: (arg1: A1, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<void>;
export function bindCallback<A1, A2, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<any[]>;
export function bindCallback<A1, A2, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2, R3]>;
export function bindCallback<A1, A2, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2]>;
export function bindCallback<A1, A2, R1>(callbackFunc: (arg1: A1, arg2: A2, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<R1>;
export function bindCallback<A1, A2>(callbackFunc: (arg1: A1, arg2: A2, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<void>;
export function bindCallback<A1, A2, A3, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<any[]>;
export function bindCallback<A1, A2, A3, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2, R3]>;
export function bindCallback<A1, A2, A3, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2]>;
export function bindCallback<A1, A2, A3, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<R1>;
export function bindCallback<A1, A2, A3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<void>;
export function bindCallback<A1, A2, A3, A4, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<any[]>;
export function bindCallback<A1, A2, A3, A4, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2, R3]>;
export function bindCallback<A1, A2, A3, A4, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2]>;
export function bindCallback<A1, A2, A3, A4, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<R1>;
export function bindCallback<A1, A2, A3, A4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<void>;
export function bindCallback<A1, A2, A3, A4, A5, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<any[]>;
export function bindCallback<A1, A2, A3, A4, A5, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2, R3]>;
export function bindCallback<A1, A2, A3, A4, A5, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2]>;
export function bindCallback<A1, A2, A3, A4, A5, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<R1>;
export function bindCallback<A1, A2, A3, A4, A5>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: () => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<void>;
export function bindCallback<A, R>(callbackFunc: (...args: Array<A | ((result: R) => any)>) => any, scheduler?: SchedulerLike): (...args: A[]) => Observable<R>;
export function bindCallback<A, R>(callbackFunc: (...args: Array<A | ((...results: R[]) => any)>) => any, scheduler?: SchedulerLike): (...args: A[]) => Observable<R[]>;
export function bindCallback(callbackFunc: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable<any>;
// tslint:enable:max-line-length
/**
* Converts a callback API to a function that returns an Observable.
*
* <span class="informal">Give it a function `f` of type `f(x, callback)` and
* it will return a function `g` that when called as `g(x)` will output an
* Observable.</span>
*
* `bindCallback` is not an operator because its input and output are not
* Observables. The input is a function `func` with some parameters. The
* last parameter must be a callback function that `func` calls when it is
* done.
*
* The output of `bindCallback` is a function that takes the same parameters
* as `func`, except the last one (the callback). When the output function
* is called with arguments it will return an Observable. If function `func`
* calls its callback with one argument, the Observable will emit that value.
* If on the other hand the callback is called with multiple values the resulting
* Observable will emit an array with said values as arguments.
*
* It is **very important** to remember that input function `func` is not called
* when the output function is, but rather when the Observable returned by the output
* function is subscribed. This means if `func` makes an AJAX request, that request
* will be made every time someone subscribes to the resulting Observable, but not before.
*
* The last optional parameter - `scheduler` - can be used to control when the call
* to `func` happens after someone subscribes to Observable, as well as when results
* passed to callback will be emitted. By default, the subscription to an Observable calls `func`
* synchronously, but using {@link asyncScheduler} as the last parameter will defer the call to `func`,
* just like wrapping the call in `setTimeout` with a timeout of `0` would. If you were to use the async Scheduler
* and call `subscribe` on the output Observable, all function calls that are currently executing
* will end before `func` is invoked.
*
* By default, results passed to the callback are emitted immediately after `func` invokes the callback.
* In particular, if the callback is called synchronously, then the subscription of the resulting Observable
* will call the `next` function synchronously as well. If you want to defer that call,
* you may use {@link asyncScheduler} just as before. This means that by using `Scheduler.async` you can
* ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo.
*
* Note that the Observable created by the output function will always emit a single value
* and then complete immediately. If `func` calls the callback multiple times, values from subsequent
* calls will not appear in the stream. If you need to listen for multiple calls,
* you probably want to use {@link fromEvent} or {@link fromEventPattern} instead.
*
* If `func` depends on some context (`this` property) and is not already bound, the context of `func`
* will be the context that the output function has at call time. In particular, if `func`
* is called as a method of some objec and if `func` is not already bound, in order to preserve the context
* it is recommended that the context of the output function is set to that object as well.
*
* If the input function calls its callback in the "node style" (i.e. first argument to callback is
* optional error parameter signaling whether the call failed or not), {@link bindNodeCallback}
* provides convenient error handling and probably is a better choice.
* `bindCallback` will treat such functions the same as any other and error parameters
* (whether passed or not) will always be interpreted as regular callback argument.
*
* ## Examples
*
* ### Convert jQuery's getJSON to an Observable API
* ```ts
* import { bindCallback } from 'rxjs';
* import * as jQuery from 'jquery';
*
* // Suppose we have jQuery.getJSON('/my/url', callback)
* const getJSONAsObservable = bindCallback(jQuery.getJSON);
* const result = getJSONAsObservable('/my/url');
* result.subscribe(x => console.log(x), e => console.error(e));
* ```
*
* ### Receive an array of arguments passed to a callback
* ```ts
* import { bindCallback } from 'rxjs';
*
* const someFunction = (a, b, c) => {
* console.log(a); // 5
* console.log(b); // 'some string'
* console.log(c); // {someProperty: 'someValue'}
* };
*
* const boundSomeFunction = bindCallback(someFunction);
* boundSomeFunction().subscribe(values => {
* console.log(values) // [5, 'some string', {someProperty: 'someValue'}]
* });
* ```
*
* ### Compare behaviour with and without async Scheduler
* ```ts
* import { bindCallback } from 'rxjs';
*
* function iCallMyCallbackSynchronously(cb) {
* cb();
* }
*
* const boundSyncFn = bindCallback(iCallMyCallbackSynchronously);
* const boundAsyncFn = bindCallback(iCallMyCallbackSynchronously, null, Rx.Scheduler.async);
*
* boundSyncFn().subscribe(() => console.log('I was sync!'));
* boundAsyncFn().subscribe(() => console.log('I was async!'));
* console.log('This happened...');
*
* // Logs:
* // I was sync!
* // This happened...
* // I was async!
* ```
*
* ### Use bindCallback on an object method
* ```ts
* import { bindCallback } from 'rxjs';
*
* const boundMethod = bindCallback(someObject.methodWithCallback);
* boundMethod.call(someObject) // make sure methodWithCallback has access to someObject
* .subscribe(subscriber);
* ```
*
* @see {@link bindNodeCallback}
* @see {@link from}
*
* @param {function} func A function with a callback as the last parameter.
* @param {SchedulerLike} [scheduler] The scheduler on which to schedule the
* callbacks.
* @return {function(...params: *): Observable} A function which returns the
* Observable that delivers the same values the callback would deliver.
* @name bindCallback
*/
export function bindCallback<T>(
callbackFunc: Function,
resultSelector?: Function|SchedulerLike,
scheduler?: SchedulerLike
): (...args: any[]) => Observable<T> {
if (resultSelector) {
if (isScheduler(resultSelector)) {
scheduler = resultSelector;
} else {
// DEPRECATED PATH
return (...args: any[]) => bindCallback(callbackFunc, scheduler)(...args).pipe(
map((args) => isArray(args) ? resultSelector(...args) : resultSelector(args)),
);
}
}
return function (this: any, ...args: any[]): Observable<T> {
const context = this;
let subject: AsyncSubject<T>;
const params = {
context,
subject,
callbackFunc,
scheduler,
};
return new Observable<T>(subscriber => {
if (!scheduler) {
if (!subject) {
subject = new AsyncSubject<T>();
const handler = (...innerArgs: any[]) => {
subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
subject.complete();
};
try {
callbackFunc.apply(context, [...args, handler]);
} catch (err) {
if (canReportError(subject)) {
subject.error(err);
} else {
console.warn(err);
}
}
}
return subject.subscribe(subscriber);
} else {
const state: DispatchState<T> = {
args, subscriber, params,
};
return scheduler.schedule<DispatchState<T>>(dispatch, 0, state);
}
});
};
}
interface DispatchState<T> {
args: any[];
subscriber: Subscriber<T>;
params: ParamsContext<T>;
}
interface ParamsContext<T> {
callbackFunc: Function;
scheduler: SchedulerLike;
context: any;
subject: AsyncSubject<T>;
}
function dispatch<T>(this: SchedulerAction<DispatchState<T>>, state: DispatchState<T>) {
const self = this;
const { args, subscriber, params } = state;
const { callbackFunc, context, scheduler } = params;
let { subject } = params;
if (!subject) {
subject = params.subject = new AsyncSubject<T>();
const handler = (...innerArgs: any[]) => {
const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
this.add(scheduler.schedule<NextState<T>>(dispatchNext, 0, { value, subject }));
};
try {
callbackFunc.apply(context, [...args, handler]);
} catch (err) {
subject.error(err);
}
}
this.add(subject.subscribe(subscriber));
}
interface NextState<T> {
subject: AsyncSubject<T>;
value: T;
}
function dispatchNext<T>(this: SchedulerAction<NextState<T>>, state: NextState<T>) {
const { value, subject } = state;
subject.next(value);
subject.complete();
}
interface ErrorState<T> {
subject: AsyncSubject<T>;
err: any;
}
function dispatchError<T>(this: SchedulerAction<ErrorState<T>>, state: ErrorState<T>) {
const { err, subject } = state;
subject.error(err);
}

View File

@ -0,0 +1,278 @@
import { Observable } from '../Observable';
import { AsyncSubject } from '../AsyncSubject';
import { Subscriber } from '../Subscriber';
import { SchedulerAction, SchedulerLike } from '../types';
import { map } from '../operators/map';
import { canReportError } from '../util/canReportError';
import { isScheduler } from '../util/isScheduler';
import { isArray } from '../util/isArray';
/* tslint:disable:max-line-length */
/** @deprecated resultSelector is deprecated, pipe to map instead */
export function bindNodeCallback(callbackFunc: Function, resultSelector: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable<any>;
export function bindNodeCallback<R1, R2, R3, R4>(callbackFunc: (callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;
export function bindNodeCallback<R1, R2, R3>(callbackFunc: (callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2, R3]>;
export function bindNodeCallback<R1, R2>(callbackFunc: (callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): () => Observable<[R1, R2]>;
export function bindNodeCallback<R1>(callbackFunc: (callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): () => Observable<R1>;
export function bindNodeCallback(callbackFunc: (callback: (err: any) => any) => any, scheduler?: SchedulerLike): () => Observable<void>;
export function bindNodeCallback<A1, R1, R2, R3, R4>(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;
export function bindNodeCallback<A1, R1, R2, R3>(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2, R3]>;
export function bindNodeCallback<A1, R1, R2>(callbackFunc: (arg1: A1, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<[R1, R2]>;
export function bindNodeCallback<A1, R1>(callbackFunc: (arg1: A1, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<R1>;
export function bindNodeCallback<A1>(callbackFunc: (arg1: A1, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1) => Observable<void>;
export function bindNodeCallback<A1, A2, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;
export function bindNodeCallback<A1, A2, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2, R3]>;
export function bindNodeCallback<A1, A2, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<[R1, R2]>;
export function bindNodeCallback<A1, A2, R1>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<R1>;
export function bindNodeCallback<A1, A2>(callbackFunc: (arg1: A1, arg2: A2, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2) => Observable<void>;
export function bindNodeCallback<A1, A2, A3, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;
export function bindNodeCallback<A1, A2, A3, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2, R3]>;
export function bindNodeCallback<A1, A2, A3, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<[R1, R2]>;
export function bindNodeCallback<A1, A2, A3, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<R1>;
export function bindNodeCallback<A1, A2, A3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3) => Observable<void>;
export function bindNodeCallback<A1, A2, A3, A4, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;
export function bindNodeCallback<A1, A2, A3, A4, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2, R3]>;
export function bindNodeCallback<A1, A2, A3, A4, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<[R1, R2]>;
export function bindNodeCallback<A1, A2, A3, A4, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<R1>;
export function bindNodeCallback<A1, A2, A3, A4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Observable<void>;
export function bindNodeCallback<A1, A2, A3, A4, A5, R1, R2, R3, R4>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2, res3: R3, res4: R4, ...args: any[]) => any) => any, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;
export function bindNodeCallback<A1, A2, A3, A4, A5, R1, R2, R3>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2, res3: R3) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2, R3]>;
export function bindNodeCallback<A1, A2, A3, A4, A5, R1, R2>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1, res2: R2) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<[R1, R2]>;
export function bindNodeCallback<A1, A2, A3, A4, A5, R1>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, res1: R1) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<R1>;
export function bindNodeCallback<A1, A2, A3, A4, A5>(callbackFunc: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any) => any) => any, scheduler?: SchedulerLike): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Observable<void>; /* tslint:enable:max-line-length */
export function bindNodeCallback(callbackFunc: Function, scheduler?: SchedulerLike): (...args: any[]) => Observable<any[]>;
/**
* Converts a Node.js-style callback API to a function that returns an
* Observable.
*
* <span class="informal">It's just like {@link bindCallback}, but the
* callback is expected to be of type `callback(error, result)`.</span>
*
* `bindNodeCallback` is not an operator because its input and output are not
* Observables. The input is a function `func` with some parameters, but the
* last parameter must be a callback function that `func` calls when it is
* done. The callback function is expected to follow Node.js conventions,
* where the first argument to the callback is an error object, signaling
* whether call was successful. If that object is passed to callback, it means
* something went wrong.
*
* The output of `bindNodeCallback` is a function that takes the same
* parameters as `func`, except the last one (the callback). When the output
* function is called with arguments, it will return an Observable.
* If `func` calls its callback with error parameter present, Observable will
* error with that value as well. If error parameter is not passed, Observable will emit
* second parameter. If there are more parameters (third and so on),
* Observable will emit an array with all arguments, except first error argument.
*
* Note that `func` will not be called at the same time output function is,
* but rather whenever resulting Observable is subscribed. By default call to
* `func` will happen synchronously after subscription, but that can be changed
* with proper `scheduler` provided as optional third parameter. {@link SchedulerLike}
* can also control when values from callback will be emitted by Observable.
* To find out more, check out documentation for {@link bindCallback}, where
* {@link SchedulerLike} works exactly the same.
*
* As in {@link bindCallback}, context (`this` property) of input function will be set to context
* of returned function, when it is called.
*
* After Observable emits value, it will complete immediately. This means
* even if `func` calls callback again, values from second and consecutive
* calls will never appear on the stream. If you need to handle functions
* that call callbacks multiple times, check out {@link fromEvent} or
* {@link fromEventPattern} instead.
*
* Note that `bindNodeCallback` can be used in non-Node.js environments as well.
* "Node.js-style" callbacks are just a convention, so if you write for
* browsers or any other environment and API you use implements that callback style,
* `bindNodeCallback` can be safely used on that API functions as well.
*
* Remember that Error object passed to callback does not have to be an instance
* of JavaScript built-in `Error` object. In fact, it does not even have to an object.
* Error parameter of callback function is interpreted as "present", when value
* of that parameter is truthy. It could be, for example, non-zero number, non-empty
* string or boolean `true`. In all of these cases resulting Observable would error
* with that value. This means usually regular style callbacks will fail very often when
* `bindNodeCallback` is used. If your Observable errors much more often then you
* would expect, check if callback really is called in Node.js-style and, if not,
* switch to {@link bindCallback} instead.
*
* Note that even if error parameter is technically present in callback, but its value
* is falsy, it still won't appear in array emitted by Observable.
*
* ## Examples
* ### Read a file from the filesystem and get the data as an Observable
* ```ts
* import * as fs from 'fs';
* const readFileAsObservable = bindNodeCallback(fs.readFile);
* const result = readFileAsObservable('./roadNames.txt', 'utf8');
* result.subscribe(x => console.log(x), e => console.error(e));
* ```
*
* ### Use on function calling callback with multiple arguments
* ```ts
* someFunction((err, a, b) => {
* console.log(err); // null
* console.log(a); // 5
* console.log(b); // "some string"
* });
* const boundSomeFunction = bindNodeCallback(someFunction);
* boundSomeFunction()
* .subscribe(value => {
* console.log(value); // [5, "some string"]
* });
* ```
*
* ### Use on function calling callback in regular style
* ```ts
* someFunction(a => {
* console.log(a); // 5
* });
* const boundSomeFunction = bindNodeCallback(someFunction);
* boundSomeFunction()
* .subscribe(
* value => {} // never gets called
* err => console.log(err) // 5
* );
* ```
*
* @see {@link bindCallback}
* @see {@link from}
*
* @param {function} func Function with a Node.js-style callback as the last parameter.
* @param {SchedulerLike} [scheduler] The scheduler on which to schedule the
* callbacks.
* @return {function(...params: *): Observable} A function which returns the
* Observable that delivers the same values the Node.js callback would
* deliver.
* @name bindNodeCallback
*/
export function bindNodeCallback<T>(
callbackFunc: Function,
resultSelector: Function|SchedulerLike,
scheduler?: SchedulerLike
): (...args: any[]) => Observable<T> {
if (resultSelector) {
if (isScheduler(resultSelector)) {
scheduler = resultSelector;
} else {
// DEPRECATED PATH
return (...args: any[]) => bindNodeCallback(callbackFunc, scheduler)(...args).pipe(
map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))
);
}
}
return function(this: any, ...args: any[]): Observable<T> {
const params: ParamsState<T> = {
subject: undefined,
args,
callbackFunc,
scheduler,
context: this,
};
return new Observable<T>(subscriber => {
const { context } = params;
let { subject } = params;
if (!scheduler) {
if (!subject) {
subject = params.subject = new AsyncSubject<T>();
const handler = (...innerArgs: any[]) => {
const err = innerArgs.shift();
if (err) {
subject.error(err);
return;
}
subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
subject.complete();
};
try {
callbackFunc.apply(context, [...args, handler]);
} catch (err) {
if (canReportError(subject)) {
subject.error(err);
} else {
console.warn(err);
}
}
}
return subject.subscribe(subscriber);
} else {
return scheduler.schedule<DispatchState<T>>(dispatch, 0, { params, subscriber, context });
}
});
};
}
interface DispatchState<T> {
subscriber: Subscriber<T>;
context: any;
params: ParamsState<T>;
}
interface ParamsState<T> {
callbackFunc: Function;
args: any[];
scheduler: SchedulerLike;
subject: AsyncSubject<T>;
context: any;
}
function dispatch<T>(this: SchedulerAction<DispatchState<T>>, state: DispatchState<T>) {
const { params, subscriber, context } = state;
const { callbackFunc, args, scheduler } = params;
let subject = params.subject;
if (!subject) {
subject = params.subject = new AsyncSubject<T>();
const handler = (...innerArgs: any[]) => {
const err = innerArgs.shift();
if (err) {
this.add(scheduler.schedule<DispatchErrorArg<T>>(dispatchError, 0, { err, subject }));
} else {
const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
this.add(scheduler.schedule<DispatchNextArg<T>>(dispatchNext, 0, { value, subject }));
}
};
try {
callbackFunc.apply(context, [...args, handler]);
} catch (err) {
this.add(scheduler.schedule<DispatchErrorArg<T>>(dispatchError, 0, { err, subject }));
}
}
this.add(subject.subscribe(subscriber));
}
interface DispatchNextArg<T> {
subject: AsyncSubject<T>;
value: T;
}
function dispatchNext<T>(arg: DispatchNextArg<T>) {
const { value, subject } = arg;
subject.next(value);
subject.complete();
}
interface DispatchErrorArg<T> {
subject: AsyncSubject<T>;
err: any;
}
function dispatchError<T>(arg: DispatchErrorArg<T>) {
const { err, subject } = arg;
subject.error(err);
}

View File

@ -0,0 +1,328 @@
import { Observable } from '../Observable';
import { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';
import { isScheduler } from '../util/isScheduler';
import { isArray } from '../util/isArray';
import { Subscriber } from '../Subscriber';
import { OuterSubscriber } from '../OuterSubscriber';
import { Operator } from '../Operator';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { fromArray } from './fromArray';
const NONE = {};
/* tslint:disable:max-line-length */
// If called with a single array, it "auto-spreads" the array, with result selector
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, R>(sources: [O1], resultSelector: (v1: ObservedValueOf<O1>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, R>(sources: [O1, O2], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(sources: [O1, O2, O3], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4, O5], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(sources: [O1, O2, O3, O4, O5, O6], resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O extends ObservableInput<any>, R>(sources: O[], resultSelector: (...args: ObservedValueOf<O>[]) => R, scheduler?: SchedulerLike): Observable<R>;
// standard call, but with a result selector
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, R>(v1: O1, resultSelector: (v1: ObservedValueOf<O1>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, R>(v1: O1, v2: O2, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R, scheduler?: SchedulerLike): Observable<R>;
// With a scheduler (deprecated)
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>>(sources: [O1], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(sources: [O1, O2], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(sources: [O1, O2, O3], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(sources: [O1, O2, O3, O4], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5, O6], scheduler: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O extends ObservableInput<any>>(sources: O[], scheduler: SchedulerLike): Observable<ObservedValueOf<O>[]>;
// Best case
export function combineLatest<O1 extends ObservableInput<any>>(sources: [O1]): Observable<[ObservedValueOf<O1>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(sources: [O1, O2]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(sources: [O1, O2, O3]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(sources: [O1, O2, O3, O4]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(sources: [O1, O2, O3, O4, O5, O6]): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;
export function combineLatest<O extends ObservableInput<any>>(sources: O[]): Observable<ObservedValueOf<O>[]>;
// Standard calls
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>>(v1: O1, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler?: SchedulerLike): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O extends ObservableInput<any>>(...observables: O[]): Observable<any[]>;
/** @deprecated Pass arguments in a single array instead `combineLatest([a, b, c])` */
export function combineLatest<O extends ObservableInput<any>, R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function combineLatest<O extends ObservableInput<any>, R>(array: O[], resultSelector: (...values: ObservedValueOf<O>[]) => R, scheduler?: SchedulerLike): Observable<R>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O extends ObservableInput<any>>(...observables: Array<O | SchedulerLike>): Observable<any[]>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<O extends ObservableInput<any>, R>(...observables: Array<O | ((...values: ObservedValueOf<O>[]) => R) | SchedulerLike>): Observable<R>;
/** @deprecated Passing a scheduler here is deprecated, use {@link subscribeOn} and/or {@link observeOn} instead */
export function combineLatest<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R) | SchedulerLike>): Observable<R>;
/* tslint:enable:max-line-length */
/**
* Combines multiple Observables to create an Observable whose values are
* calculated from the latest values of each of its input Observables.
*
* <span class="informal">Whenever any input Observable emits a value, it
* computes a formula using the latest values from all the inputs, then emits
* the output of that formula.</span>
*
* ![](combineLatest.png)
*
* `combineLatest` combines the values from all the Observables passed as
* arguments. This is done by subscribing to each Observable in order and,
* whenever any Observable emits, collecting an array of the most recent
* values from each Observable. So if you pass `n` Observables to operator,
* returned Observable will always emit an array of `n` values, in order
* corresponding to order of passed Observables (value from the first Observable
* on the first place and so on).
*
* Static version of `combineLatest` accepts either an array of Observables
* or each Observable can be put directly as an argument. Note that array of
* Observables is good choice, if you don't know beforehand how many Observables
* you will combine. Passing empty array will result in Observable that
* completes immediately.
*
* To ensure output array has always the same length, `combineLatest` will
* actually wait for all input Observables to emit at least once,
* before it starts emitting results. This means if some Observable emits
* values before other Observables started emitting, all these values but the last
* will be lost. On the other hand, if some Observable does not emit a value but
* completes, resulting Observable will complete at the same moment without
* emitting anything, since it will be now impossible to include value from
* completed Observable in resulting array. Also, if some input Observable does
* not emit any value and never completes, `combineLatest` will also never emit
* and never complete, since, again, it will wait for all streams to emit some
* value.
*
* If at least one Observable was passed to `combineLatest` and all passed Observables
* emitted something, resulting Observable will complete when all combined
* streams complete. So even if some Observable completes, result of
* `combineLatest` will still emit values when other Observables do. In case
* of completed Observable, its value from now on will always be the last
* emitted value. On the other hand, if any Observable errors, `combineLatest`
* will error immediately as well, and all other Observables will be unsubscribed.
*
* `combineLatest` accepts as optional parameter `project` function, which takes
* as arguments all values that would normally be emitted by resulting Observable.
* `project` can return any kind of value, which will be then emitted by Observable
* instead of default array. Note that `project` does not take as argument that array
* of values, but values themselves. That means default `project` can be imagined
* as function that takes all its arguments and puts them into an array.
*
* ## Examples
* ### Combine two timer Observables
* ```ts
* import { combineLatest, timer } from 'rxjs';
*
* const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
* const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
* const combinedTimers = combineLatest(firstTimer, secondTimer);
* combinedTimers.subscribe(value => console.log(value));
* // Logs
* // [0, 0] after 0.5s
* // [1, 0] after 1s
* // [1, 1] after 1.5s
* // [2, 1] after 2s
* ```
*
* ### Combine an array of Observables
* ```ts
* import { combineLatest, of } from 'rxjs';
* import { delay, starWith } from 'rxjs/operators';
*
* const observables = [1, 5, 10].map(
* n => of(n).pipe(
* delay(n * 1000), // emit 0 and then emit n after n seconds
* startWith(0),
* )
* );
* const combined = combineLatest(observables);
* combined.subscribe(value => console.log(value));
* // Logs
* // [0, 0, 0] immediately
* // [1, 0, 0] after 1s
* // [1, 5, 0] after 5s
* // [1, 5, 10] after 10s
* ```
*
*
* ### Use project function to dynamically calculate the Body-Mass Index
* ```ts
* import { combineLatest, of } from 'rxjs';
* import { map } from 'rxjs/operators';
*
* const weight = of(70, 72, 76, 79, 75);
* const height = of(1.76, 1.77, 1.78);
* const bmi = combineLatest(weight, height).pipe(
* map(([w, h]) => w / (h * h)),
* );
* bmi.subscribe(x => console.log('BMI is ' + x));
*
* // With output to console:
* // BMI is 24.212293388429753
* // BMI is 23.93948099205209
* // BMI is 23.671253629592222
* ```
*
* @see {@link combineAll}
* @see {@link merge}
* @see {@link withLatestFrom}
*
* @param {ObservableInput} observable1 An input Observable to combine with other Observables.
* @param {ObservableInput} observable2 An input Observable to combine with other Observables.
* More than one input Observables may be given as arguments
* or an array of Observables may be given as the first argument.
* @param {function} [project] An optional function to project the values from
* the combined latest values into a new value on the output Observable.
* @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for subscribing to
* each input Observable.
* @return {Observable} An Observable of projected values from the most recent
* values from each input Observable, or an array of the most recent values from
* each input Observable.
*/
export function combineLatest<O extends ObservableInput<any>, R>(
...observables: (O | ((...values: ObservedValueOf<O>[]) => R) | SchedulerLike)[]
): Observable<R> {
let resultSelector: (...values: Array<any>) => R = null;
let scheduler: SchedulerLike = null;
if (isScheduler(observables[observables.length - 1])) {
scheduler = observables.pop() as SchedulerLike;
}
if (typeof observables[observables.length - 1] === 'function') {
resultSelector = observables.pop() as (...values: Array<any>) => R;
}
// if the first and only other argument besides the resultSelector is an array
// assume it's been called with `combineLatest([obs1, obs2, obs3], resultSelector)`
if (observables.length === 1 && isArray(observables[0])) {
observables = observables[0] as any;
}
return fromArray(observables, scheduler).lift(new CombineLatestOperator<ObservedValueOf<O>, R>(resultSelector));
}
export class CombineLatestOperator<T, R> implements Operator<T, R> {
constructor(private resultSelector?: (...values: Array<any>) => R) {
}
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class CombineLatestSubscriber<T, R> extends OuterSubscriber<T, R> {
private active: number = 0;
private values: any[] = [];
private observables: any[] = [];
private toRespond: number;
constructor(destination: Subscriber<R>, private resultSelector?: (...values: Array<any>) => R) {
super(destination);
}
protected _next(observable: any) {
this.values.push(NONE);
this.observables.push(observable);
}
protected _complete() {
const observables = this.observables;
const len = observables.length;
if (len === 0) {
this.destination.complete();
} else {
this.active = len;
this.toRespond = len;
for (let i = 0; i < len; i++) {
const observable = observables[i];
this.add(subscribeToResult(this, observable, observable, i));
}
}
}
notifyComplete(unused: Subscriber<R>): void {
if ((this.active -= 1) === 0) {
this.destination.complete();
}
}
notifyNext(outerValue: T, innerValue: R,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
const values = this.values;
const oldVal = values[outerIndex];
const toRespond = !this.toRespond
? 0
: oldVal === NONE ? --this.toRespond : this.toRespond;
values[outerIndex] = innerValue;
if (toRespond === 0) {
if (this.resultSelector) {
this._tryResultSelector(values);
} else {
this.destination.next(values.slice());
}
}
}
private _tryResultSelector(values: any[]) {
let result: any;
try {
result = this.resultSelector.apply(this, values);
} catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
}
}

147
node_modules/rxjs/src/internal/observable/concat.ts generated vendored Normal file
View File

@ -0,0 +1,147 @@
import { Observable } from '../Observable';
import { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';
import { isScheduler } from '../util/isScheduler';
import { of } from './of';
import { from } from './from';
import { concatAll } from '../operators/concatAll';
/* tslint:disable:max-line-length */
/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */
export function concat<O1 extends ObservableInput<any>>(v1: O1, scheduler: SchedulerLike): Observable<ObservedValueOf<O1>>;
/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2>>;
/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3>>;
/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4>>;
/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5>>;
/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, scheduler: SchedulerLike): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5> | ObservedValueOf<O6>>;
export function concat<O1 extends ObservableInput<any>>(v1: O1): Observable<ObservedValueOf<O1>>;
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2): Observable<ObservedValueOf<O1> | ObservedValueOf<O2>>;
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3>>;
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4>>;
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5>>;
export function concat<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable<ObservedValueOf<O1> | ObservedValueOf<O2> | ObservedValueOf<O3> | ObservedValueOf<O4> | ObservedValueOf<O5> | ObservedValueOf<O6>>;
export function concat<O extends ObservableInput<any>>(...observables: O[]): Observable<ObservedValueOf<O>>;
/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */
export function concat<O extends ObservableInput<any>>(...observables: (O | SchedulerLike)[]): Observable<ObservedValueOf<O>>;
export function concat<R>(...observables: ObservableInput<any>[]): Observable<R>;
/** @deprecated Use {@link scheduled} and {@link concatAll} (e.g. `scheduled([o1, o2, o3], scheduler).pipe(concatAll())`) */
export function concat<R>(...observables: (ObservableInput<any> | SchedulerLike)[]): Observable<R>;
/* tslint:enable:max-line-length */
/**
* Creates an output Observable which sequentially emits all values from given
* Observable and then moves on to the next.
*
* <span class="informal">Concatenates multiple Observables together by
* sequentially emitting their values, one Observable after the other.</span>
*
* ![](concat.png)
*
* `concat` joins multiple Observables together, by subscribing to them one at a time and
* merging their results into the output Observable. You can pass either an array of
* Observables, or put them directly as arguments. Passing an empty array will result
* in Observable that completes immediately.
*
* `concat` will subscribe to first input Observable and emit all its values, without
* changing or affecting them in any way. When that Observable completes, it will
* subscribe to then next Observable passed and, again, emit its values. This will be
* repeated, until the operator runs out of Observables. When last input Observable completes,
* `concat` will complete as well. At any given moment only one Observable passed to operator
* emits values. If you would like to emit values from passed Observables concurrently, check out
* {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
* `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
*
* Note that if some input Observable never completes, `concat` will also never complete
* and Observables following the one that did not complete will never be subscribed. On the other
* hand, if some Observable simply completes immediately after it is subscribed, it will be
* invisible for `concat`, which will just move on to the next Observable.
*
* If any Observable in chain errors, instead of passing control to the next Observable,
* `concat` will error immediately as well. Observables that would be subscribed after
* the one that emitted error, never will.
*
* If you pass to `concat` the same Observable many times, its stream of values
* will be "replayed" on every subscription, which means you can repeat given Observable
* as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
* you can always use {@link repeat}.
*
* ## Examples
* ### Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10
* ```ts
* import { concat, interval, range } from 'rxjs';
* import { take } from 'rxjs/operators';
*
* const timer = interval(1000).pipe(take(4));
* const sequence = range(1, 10);
* const result = concat(timer, sequence);
* result.subscribe(x => console.log(x));
*
* // results in:
* // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
* ```
*
* ### Concatenate 3 Observables
* ```ts
* import { concat, interval } from 'rxjs';
* import { take } from 'rxjs/operators';
*
* const timer1 = interval(1000).pipe(take(10));
* const timer2 = interval(2000).pipe(take(6));
* const timer3 = interval(500).pipe(take(10));
*
* const result = concat(timer1, timer2, timer3);
* result.subscribe(x => console.log(x));
*
* // results in the following:
* // (Prints to console sequentially)
* // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
* // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
* // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
* ```
*
* ### Concatenate the same Observable to repeat it
* ```ts
* import { concat, interval } from 'rxjs';
* import { take } from 'rxjs/operators';
*
* const timer = interval(1000).pipe(take(2));
*
* concat(timer, timer) // concatenating the same Observable!
* .subscribe(
* value => console.log(value),
* err => {},
* () => console.log('...and it is done!')
* );
*
* // Logs:
* // 0 after 1s
* // 1 after 2s
* // 0 after 3s
* // 1 after 4s
* // "...and it is done!" also after 4s
* ```
*
* @see {@link concatAll}
* @see {@link concatMap}
* @see {@link concatMapTo}
* @see {@link startWith}
* @see {@link endWith}
*
* @param {ObservableInput} input1 An input Observable to concatenate with others.
* @param {ObservableInput} input2 An input Observable to concatenate with others.
* More than one input Observables may be given as argument.
* @param {SchedulerLike} [scheduler=null] An optional {@link SchedulerLike} to schedule each
* Observable subscription on.
* @return {Observable} All values of each passed Observable merged into a
* single Observable, in order, in serial fashion.
* @static true
* @name concat
* @owner Observable
*/
export function concat<O extends ObservableInput<any>, R>(...observables: Array<O | SchedulerLike>): Observable<ObservedValueOf<O> | R> {
return concatAll<R>()(of(...observables));
}

67
node_modules/rxjs/src/internal/observable/defer.ts generated vendored Normal file
View File

@ -0,0 +1,67 @@
import { Observable } from '../Observable';
import { SubscribableOrPromise, ObservedValueOf, ObservableInput } from '../types';
import { from } from './from'; // lol
import { empty } from './empty';
/**
* Creates an Observable that, on subscribe, calls an Observable factory to
* make an Observable for each new Observer.
*
* <span class="informal">Creates the Observable lazily, that is, only when it
* is subscribed.
* </span>
*
* ![](defer.png)
*
* `defer` allows you to create the Observable only when the Observer
* subscribes, and create a fresh Observable for each Observer. It waits until
* an Observer subscribes to it, and then it generates an Observable,
* typically with an Observable factory function. It does this afresh for each
* subscriber, so although each subscriber may think it is subscribing to the
* same Observable, in fact each subscriber gets its own individual
* Observable.
*
* ## Example
* ### Subscribe to either an Observable of clicks or an Observable of interval, at random
* ```ts
* import { defer, fromEvent, interval } from 'rxjs';
*
* const clicksOrInterval = defer(function () {
* return Math.random() > 0.5
* ? fromEvent(document, 'click')
* : interval(1000);
* });
* clicksOrInterval.subscribe(x => console.log(x));
*
* // Results in the following behavior:
* // If the result of Math.random() is greater than 0.5 it will listen
* // for clicks anywhere on the "document"; when document is clicked it
* // will log a MouseEvent object to the console. If the result is less
* // than 0.5 it will emit ascending numbers, one every second(1000ms).
* ```
*
* @see {@link Observable}
*
* @param {function(): SubscribableOrPromise} observableFactory The Observable
* factory function to invoke for each Observer that subscribes to the output
* Observable. May also return a Promise, which will be converted on the fly
* to an Observable.
* @return {Observable} An Observable whose Observers' subscriptions trigger
* an invocation of the given Observable factory function.
* @static true
* @name defer
* @owner Observable
*/
export function defer<R extends ObservableInput<any> | void>(observableFactory: () => R): Observable<ObservedValueOf<R>> {
return new Observable<ObservedValueOf<R>>(subscriber => {
let input: R | void;
try {
input = observableFactory();
} catch (err) {
subscriber.error(err);
return undefined;
}
const source = input ? from(input as ObservableInput<ObservedValueOf<R>>) : empty();
return source.subscribe(subscriber);
});
}

View File

@ -0,0 +1,550 @@
import { root } from '../../util/root';
import { Observable } from '../../Observable';
import { Subscriber } from '../../Subscriber';
import { TeardownLogic } from '../../types';
import { map } from '../../operators/map';
export interface AjaxRequest {
url?: string;
body?: any;
user?: string;
async?: boolean;
method?: string;
headers?: Object;
timeout?: number;
password?: string;
hasContent?: boolean;
crossDomain?: boolean;
withCredentials?: boolean;
createXHR?: () => XMLHttpRequest;
progressSubscriber?: Subscriber<any>;
responseType?: string;
}
function getCORSRequest(): XMLHttpRequest {
if (root.XMLHttpRequest) {
return new root.XMLHttpRequest();
} else if (!!root.XDomainRequest) {
return new root.XDomainRequest();
} else {
throw new Error('CORS is not supported by your browser');
}
}
function getXMLHttpRequest(): XMLHttpRequest {
if (root.XMLHttpRequest) {
return new root.XMLHttpRequest();
} else {
let progId: string;
try {
const progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
for (let i = 0; i < 3; i++) {
try {
progId = progIds[i];
if (new root.ActiveXObject(progId)) {
break;
}
} catch (e) {
//suppress exceptions
}
}
return new root.ActiveXObject(progId);
} catch (e) {
throw new Error('XMLHttpRequest is not supported by your browser');
}
}
}
export interface AjaxCreationMethod {
(urlOrRequest: string | AjaxRequest): Observable<AjaxResponse>;
get(url: string, headers?: Object): Observable<AjaxResponse>;
post(url: string, body?: any, headers?: Object): Observable<AjaxResponse>;
put(url: string, body?: any, headers?: Object): Observable<AjaxResponse>;
patch(url: string, body?: any, headers?: Object): Observable<AjaxResponse>;
delete(url: string, headers?: Object): Observable<AjaxResponse>;
getJSON<T>(url: string, headers?: Object): Observable<T>;
}
export function ajaxGet(url: string, headers: Object = null) {
return new AjaxObservable<AjaxResponse>({ method: 'GET', url, headers });
}
export function ajaxPost(url: string, body?: any, headers?: Object): Observable<AjaxResponse> {
return new AjaxObservable<AjaxResponse>({ method: 'POST', url, body, headers });
}
export function ajaxDelete(url: string, headers?: Object): Observable<AjaxResponse> {
return new AjaxObservable<AjaxResponse>({ method: 'DELETE', url, headers });
}
export function ajaxPut(url: string, body?: any, headers?: Object): Observable<AjaxResponse> {
return new AjaxObservable<AjaxResponse>({ method: 'PUT', url, body, headers });
}
export function ajaxPatch(url: string, body?: any, headers?: Object): Observable<AjaxResponse> {
return new AjaxObservable<AjaxResponse>({ method: 'PATCH', url, body, headers });
}
const mapResponse = map((x: AjaxResponse, index: number) => x.response);
export function ajaxGetJSON<T>(url: string, headers?: Object): Observable<T> {
return mapResponse(
new AjaxObservable<AjaxResponse>({
method: 'GET',
url,
responseType: 'json',
headers
})
);
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @extends {Ignored}
* @hide true
*/
export class AjaxObservable<T> extends Observable<T> {
/**
* Creates an observable for an Ajax request with either a request object with
* url, headers, etc or a string for a URL.
*
* ## Example
* ```ts
* import { ajax } from 'rxjs/ajax';
*
* const source1 = ajax('/products');
* const source2 = ajax({ url: 'products', method: 'GET' });
* ```
*
* @param {string|Object} request Can be one of the following:
* A string of the URL to make the Ajax call.
* An object with the following properties
* - url: URL of the request
* - body: The body of the request
* - method: Method of the request, such as GET, POST, PUT, PATCH, DELETE
* - async: Whether the request is async
* - headers: Optional headers
* - crossDomain: true if a cross domain request, else false
* - createXHR: a function to override if you need to use an alternate
* XMLHttpRequest implementation.
* - resultSelector: a function to use to alter the output value type of
* the Observable. Gets {@link AjaxResponse} as an argument.
* @return {Observable} An observable sequence containing the XMLHttpRequest.
* @static true
* @name ajax
* @owner Observable
* @nocollapse
*/
static create: AjaxCreationMethod = (() => {
const create: any = (urlOrRequest: string | AjaxRequest) => {
return new AjaxObservable(urlOrRequest);
};
create.get = ajaxGet;
create.post = ajaxPost;
create.delete = ajaxDelete;
create.put = ajaxPut;
create.patch = ajaxPatch;
create.getJSON = ajaxGetJSON;
return <AjaxCreationMethod>create;
})();
private request: AjaxRequest;
constructor(urlOrRequest: string | AjaxRequest) {
super();
const request: AjaxRequest = {
async: true,
createXHR: function(this: AjaxRequest) {
return this.crossDomain ? getCORSRequest() : getXMLHttpRequest();
},
crossDomain: true,
withCredentials: false,
headers: {},
method: 'GET',
responseType: 'json',
timeout: 0
};
if (typeof urlOrRequest === 'string') {
request.url = urlOrRequest;
} else {
for (const prop in urlOrRequest) {
if (urlOrRequest.hasOwnProperty(prop)) {
request[prop] = urlOrRequest[prop];
}
}
}
this.request = request;
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>): TeardownLogic {
return new AjaxSubscriber(subscriber, this.request);
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class AjaxSubscriber<T> extends Subscriber<Event> {
private xhr: XMLHttpRequest;
private done: boolean = false;
constructor(destination: Subscriber<T>, public request: AjaxRequest) {
super(destination);
const headers = request.headers = request.headers || {};
// force CORS if requested
if (!request.crossDomain && !this.getHeader(headers, 'X-Requested-With')) {
headers['X-Requested-With'] = 'XMLHttpRequest';
}
// ensure content type is set
let contentTypeHeader = this.getHeader(headers, 'Content-Type');
if (!contentTypeHeader && !(root.FormData && request.body instanceof root.FormData) && typeof request.body !== 'undefined') {
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
}
// properly serialize body
request.body = this.serializeBody(request.body, this.getHeader(request.headers, 'Content-Type'));
this.send();
}
next(e: Event): void {
this.done = true;
const { xhr, request, destination } = this;
let result;
try {
result = new AjaxResponse(e, xhr, request);
} catch (err) {
return destination.error(err);
}
destination.next(result);
}
private send(): void {
const {
request,
request: { user, method, url, async, password, headers, body }
} = this;
try {
const xhr = this.xhr = request.createXHR();
// set up the events before open XHR
// https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
// You need to add the event listeners before calling open() on the request.
// Otherwise the progress events will not fire.
this.setupEvents(xhr, request);
// open XHR
if (user) {
xhr.open(method, url, async, user, password);
} else {
xhr.open(method, url, async);
}
// timeout, responseType and withCredentials can be set once the XHR is open
if (async) {
xhr.timeout = request.timeout;
xhr.responseType = request.responseType as any;
}
if ('withCredentials' in xhr) {
xhr.withCredentials = !!request.withCredentials;
}
// set headers
this.setHeaders(xhr, headers);
// finally send the request
if (body) {
xhr.send(body);
} else {
xhr.send();
}
} catch (err) {
this.error(err);
}
}
private serializeBody(body: any, contentType?: string) {
if (!body || typeof body === 'string') {
return body;
} else if (root.FormData && body instanceof root.FormData) {
return body;
}
if (contentType) {
const splitIndex = contentType.indexOf(';');
if (splitIndex !== -1) {
contentType = contentType.substring(0, splitIndex);
}
}
switch (contentType) {
case 'application/x-www-form-urlencoded':
return Object.keys(body).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`).join('&');
case 'application/json':
return JSON.stringify(body);
default:
return body;
}
}
private setHeaders(xhr: XMLHttpRequest, headers: Object) {
for (let key in headers) {
if (headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, headers[key]);
}
}
}
private getHeader(headers: {}, headerName: string): any {
for (let key in headers) {
if (key.toLowerCase() === headerName.toLowerCase()) {
return headers[key];
}
}
return undefined;
}
private setupEvents(xhr: XMLHttpRequest, request: AjaxRequest) {
const progressSubscriber = request.progressSubscriber;
function xhrTimeout(this: XMLHttpRequest, e: ProgressEvent): void {
const {subscriber, progressSubscriber, request } = (<any>xhrTimeout);
if (progressSubscriber) {
progressSubscriber.error(e);
}
let error;
try {
error = new AjaxTimeoutError(this, request); // TODO: Make betterer.
} catch (err) {
error = err;
}
subscriber.error(error);
}
xhr.ontimeout = xhrTimeout;
(<any>xhrTimeout).request = request;
(<any>xhrTimeout).subscriber = this;
(<any>xhrTimeout).progressSubscriber = progressSubscriber;
if (xhr.upload && 'withCredentials' in xhr) {
if (progressSubscriber) {
let xhrProgress: (e: ProgressEvent) => void;
xhrProgress = function(e: ProgressEvent) {
const { progressSubscriber } = (<any>xhrProgress);
progressSubscriber.next(e);
};
if (root.XDomainRequest) {
xhr.onprogress = xhrProgress;
} else {
xhr.upload.onprogress = xhrProgress;
}
(<any>xhrProgress).progressSubscriber = progressSubscriber;
}
let xhrError: (e: any) => void;
xhrError = function(this: XMLHttpRequest, e: ErrorEvent) {
const { progressSubscriber, subscriber, request } = (<any>xhrError);
if (progressSubscriber) {
progressSubscriber.error(e);
}
let error;
try {
error = new AjaxError('ajax error', this, request);
} catch (err) {
error = err;
}
subscriber.error(error);
};
xhr.onerror = xhrError;
(<any>xhrError).request = request;
(<any>xhrError).subscriber = this;
(<any>xhrError).progressSubscriber = progressSubscriber;
}
function xhrReadyStateChange(this: XMLHttpRequest, e: Event) {
return;
}
xhr.onreadystatechange = xhrReadyStateChange;
(<any>xhrReadyStateChange).subscriber = this;
(<any>xhrReadyStateChange).progressSubscriber = progressSubscriber;
(<any>xhrReadyStateChange).request = request;
function xhrLoad(this: XMLHttpRequest, e: Event) {
const { subscriber, progressSubscriber, request } = (<any>xhrLoad);
if (this.readyState === 4) {
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
let status: number = this.status === 1223 ? 204 : this.status;
let response: any = (this.responseType === 'text' ? (
this.response || this.responseText) : this.response);
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : 0;
}
// 4xx and 5xx should error (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
if (status < 400) {
if (progressSubscriber) {
progressSubscriber.complete();
}
subscriber.next(e);
subscriber.complete();
} else {
if (progressSubscriber) {
progressSubscriber.error(e);
}
let error;
try {
error = new AjaxError('ajax error ' + status, this, request);
} catch (err) {
error = err;
}
subscriber.error(error);
}
}
}
xhr.onload = xhrLoad;
(<any>xhrLoad).subscriber = this;
(<any>xhrLoad).progressSubscriber = progressSubscriber;
(<any>xhrLoad).request = request;
}
unsubscribe() {
const { done, xhr } = this;
if (!done && xhr && xhr.readyState !== 4 && typeof xhr.abort === 'function') {
xhr.abort();
}
super.unsubscribe();
}
}
/**
* A normalized AJAX response.
*
* @see {@link ajax}
*
* @class AjaxResponse
*/
export class AjaxResponse {
/** @type {number} The HTTP status code */
status: number;
/** @type {string|ArrayBuffer|Document|object|any} The response data */
response: any;
/** @type {string} The raw responseText */
responseText: string;
/** @type {string} The responseType (e.g. 'json', 'arraybuffer', or 'xml') */
responseType: string;
constructor(public originalEvent: Event, public xhr: XMLHttpRequest, public request: AjaxRequest) {
this.status = xhr.status;
this.responseType = xhr.responseType || request.responseType;
this.response = parseXhrResponse(this.responseType, xhr);
}
}
export type AjaxErrorNames = 'AjaxError' | 'AjaxTimeoutError';
/**
* A normalized AJAX error.
*
* @see {@link ajax}
*
* @class AjaxError
*/
export interface AjaxError extends Error {
/** @type {XMLHttpRequest} The XHR instance associated with the error */
xhr: XMLHttpRequest;
/** @type {AjaxRequest} The AjaxRequest associated with the error */
request: AjaxRequest;
/** @type {number} The HTTP status code */
status: number;
/** @type {string} The responseType (e.g. 'json', 'arraybuffer', or 'xml') */
responseType: string;
/** @type {string|ArrayBuffer|Document|object|any} The response data */
response: any;
}
export interface AjaxErrorCtor {
new(message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError;
}
const AjaxErrorImpl = (() => {
function AjaxErrorImpl(this: any, message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError {
Error.call(this);
this.message = message;
this.name = 'AjaxError';
this.xhr = xhr;
this.request = request;
this.status = xhr.status;
this.responseType = xhr.responseType || request.responseType;
this.response = parseXhrResponse(this.responseType, xhr);
return this;
}
AjaxErrorImpl.prototype = Object.create(Error.prototype);
return AjaxErrorImpl;
})();
export const AjaxError: AjaxErrorCtor = AjaxErrorImpl as any;
function parseJson(xhr: XMLHttpRequest) {
// HACK(benlesh): TypeScript shennanigans
// tslint:disable-next-line:no-any XMLHttpRequest is defined to always have 'response' inferring xhr as never for the else clause.
if ('response' in (xhr as any)) {
//IE does not support json as responseType, parse it internally
return xhr.responseType ? xhr.response : JSON.parse(xhr.response || xhr.responseText || 'null');
} else {
return JSON.parse((xhr as any).responseText || 'null');
}
}
function parseXhrResponse(responseType: string, xhr: XMLHttpRequest) {
switch (responseType) {
case 'json':
return parseJson(xhr);
case 'xml':
return xhr.responseXML;
case 'text':
default:
// HACK(benlesh): TypeScript shennanigans
// tslint:disable-next-line:no-any XMLHttpRequest is defined to always have 'response' inferring xhr as never for the else sub-expression.
return ('response' in (xhr as any)) ? xhr.response : xhr.responseText;
}
}
export interface AjaxTimeoutError extends AjaxError {
}
export interface AjaxTimeoutErrorCtor {
new(xhr: XMLHttpRequest, request: AjaxRequest): AjaxTimeoutError;
}
function AjaxTimeoutErrorImpl(this: any, xhr: XMLHttpRequest, request: AjaxRequest) {
AjaxError.call(this, 'ajax timeout', xhr, request);
this.name = 'AjaxTimeoutError';
return this;
}
/**
* @see {@link ajax}
*
* @class AjaxTimeoutError
*/
export const AjaxTimeoutError: AjaxTimeoutErrorCtor = AjaxTimeoutErrorImpl as any;

View File

@ -0,0 +1,77 @@
import { Subscriber } from '../../Subscriber';
import { AjaxResponse } from './AjaxObservable';
/**
* @see {@link ajax}
*
* @interface
* @name AjaxRequest
* @noimport true
*/
export class AjaxRequestDoc {
/**
* @type {string}
*/
url: string = '';
/**
* @type {number}
*/
body: any = 0;
/**
* @type {string}
*/
user: string = '';
/**
* @type {boolean}
*/
async: boolean = false;
/**
* @type {string}
*/
method: string = '';
/**
* @type {Object}
*/
headers: Object = null;
/**
* @type {number}
*/
timeout: number = 0;
/**
* @type {string}
*/
password: string = '';
/**
* @type {boolean}
*/
hasContent: boolean = false;
/**
* @type {boolean}
*/
crossDomain: boolean = false;
/**
* @type {boolean}
*/
withCredentials: boolean = false;
/**
* @return {XMLHttpRequest}
*/
createXHR(): XMLHttpRequest {
return null;
}
/**
* @type {Subscriber}
*/
progressSubscriber: Subscriber<any> = null;
/**
* @param {AjaxResponse} response
* @return {T}
*/
resultSelector<T>(response: AjaxResponse): T {
return null;
}
/**
* @type {string}
*/
responseType: string = '';
}

View File

@ -0,0 +1,387 @@
import { Subject, AnonymousSubject } from '../../Subject';
import { Subscriber } from '../../Subscriber';
import { Observable } from '../../Observable';
import { Subscription } from '../../Subscription';
import { Operator } from '../../Operator';
import { ReplaySubject } from '../../ReplaySubject';
import { Observer, NextObserver } from '../../types';
/**
* WebSocketSubjectConfig is a plain Object that allows us to make our
* webSocket configurable.
*
* <span class="informal">Provides flexibility to {@link webSocket}</span>
*
* It defines a set of properties to provide custom behavior in specific
* moments of the socket's lifecycle. When the connection opens we can
* use `openObserver`, when the connection is closed `closeObserver`, if we
* are interested in listening for data comming from server: `deserializer`,
* which allows us to customize the deserialization strategy of data before passing it
* to the socket client. By default `deserializer` is going to apply `JSON.parse` to each message comming
* from the Server.
*
* ## Example
* **deserializer**, the default for this property is `JSON.parse` but since there are just two options
* for incomming data, either be text or binarydata. We can apply a custom deserialization strategy
* or just simply skip the default behaviour.
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const wsSubject = webSocket({
* url: 'ws://localhost:8081',
* //Apply any transformation of your choice.
* deserializer: ({data}) => data
* });
*
* wsSubject.subscribe(console.log);
*
* // Let's suppose we have this on the Server: ws.send("This is a msg from the server")
* //output
* //
* // This is a msg from the server
* ```
*
* **serializer** allows us tom apply custom serialization strategy but for the outgoing messages
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const wsSubject = webSocket({
* url: 'ws://localhost:8081',
* //Apply any transformation of your choice.
* serializer: msg => JSON.stringify({channel: "webDevelopment", msg: msg})
* });
*
* wsSubject.subscribe(() => subject.next("msg to the server"));
*
* // Let's suppose we have this on the Server: ws.send("This is a msg from the server")
* //output
* //
* // {"channel":"webDevelopment","msg":"msg to the server"}
* ```
*
* **closeObserver** allows us to set a custom error when an error raise up.
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const wsSubject = webSocket({
* url: 'ws://localhost:8081',
* closeObserver: {
next(closeEvent) {
const customError = { code: 6666, reason: "Custom evil reason" }
console.log(`code: ${customError.code}, reason: ${customError.reason}`);
}
}
* });
*
* //output
* // code: 6666, reason: Custom evil reason
* ```
*
* **openObserver**, Let's say we need to make some kind of init task before sending/receiving msgs to the
* webSocket or sending notification that the connection was successful, this is when
* openObserver is usefull for.
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const wsSubject = webSocket({
* url: 'ws://localhost:8081',
* openObserver: {
* next: () => {
* console.log('connetion ok');
* }
* },
* });
*
* //output
* // connetion ok`
* ```
* */
export interface WebSocketSubjectConfig<T> {
/** The url of the socket server to connect to */
url: string;
/** The protocol to use to connect */
protocol?: string | Array<string>;
/** @deprecated use {@link deserializer} */
resultSelector?: (e: MessageEvent) => T;
/**
* A serializer used to create messages from passed values before the
* messages are sent to the server. Defaults to JSON.stringify.
*/
serializer?: (value: T) => WebSocketMessage;
/**
* A deserializer used for messages arriving on the socket from the
* server. Defaults to JSON.parse.
*/
deserializer?: (e: MessageEvent) => T;
/**
* An Observer that watches when open events occur on the underlying web socket.
*/
openObserver?: NextObserver<Event>;
/**
* An Observer than watches when close events occur on the underlying webSocket
*/
closeObserver?: NextObserver<CloseEvent>;
/**
* An Observer that watches when a close is about to occur due to
* unsubscription.
*/
closingObserver?: NextObserver<void>;
/**
* A WebSocket constructor to use. This is useful for situations like using a
* WebSocket impl in Node (WebSocket is a DOM API), or for mocking a WebSocket
* for testing purposes
*/
WebSocketCtor?: { new(url: string, protocols?: string|string[]): WebSocket };
/** Sets the `binaryType` property of the underlying WebSocket. */
binaryType?: 'blob' | 'arraybuffer';
}
const DEFAULT_WEBSOCKET_CONFIG: WebSocketSubjectConfig<any> = {
url: '',
deserializer: (e: MessageEvent) => JSON.parse(e.data),
serializer: (value: any) => JSON.stringify(value),
};
const WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT =
'WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }';
export type WebSocketMessage = string | ArrayBuffer | Blob | ArrayBufferView;
export class WebSocketSubject<T> extends AnonymousSubject<T> {
private _config: WebSocketSubjectConfig<T>;
/** @deprecated This is an internal implementation detail, do not use. */
_output: Subject<T>;
private _socket: WebSocket;
constructor(urlConfigOrSource: string | WebSocketSubjectConfig<T> | Observable<T>, destination?: Observer<T>) {
super();
if (urlConfigOrSource instanceof Observable) {
this.destination = destination;
this.source = urlConfigOrSource as Observable<T>;
} else {
const config = this._config = { ...DEFAULT_WEBSOCKET_CONFIG };
this._output = new Subject<T>();
if (typeof urlConfigOrSource === 'string') {
config.url = urlConfigOrSource;
} else {
for (let key in urlConfigOrSource) {
if (urlConfigOrSource.hasOwnProperty(key)) {
config[key] = urlConfigOrSource[key];
}
}
}
if (!config.WebSocketCtor && WebSocket) {
config.WebSocketCtor = WebSocket;
} else if (!config.WebSocketCtor) {
throw new Error('no WebSocket constructor can be found');
}
this.destination = new ReplaySubject();
}
}
lift<R>(operator: Operator<T, R>): WebSocketSubject<R> {
const sock = new WebSocketSubject<R>(this._config as WebSocketSubjectConfig<any>, <any> this.destination);
sock.operator = operator;
sock.source = this;
return sock;
}
private _resetState() {
this._socket = null;
if (!this.source) {
this.destination = new ReplaySubject();
}
this._output = new Subject<T>();
}
/**
* Creates an {@link Observable}, that when subscribed to, sends a message,
* defined by the `subMsg` function, to the server over the socket to begin a
* subscription to data over that socket. Once data arrives, the
* `messageFilter` argument will be used to select the appropriate data for
* the resulting Observable. When teardown occurs, either due to
* unsubscription, completion or error, a message defined by the `unsubMsg`
* argument will be send to the server over the WebSocketSubject.
*
* @param subMsg A function to generate the subscription message to be sent to
* the server. This will still be processed by the serializer in the
* WebSocketSubject's config. (Which defaults to JSON serialization)
* @param unsubMsg A function to generate the unsubscription message to be
* sent to the server at teardown. This will still be processed by the
* serializer in the WebSocketSubject's config.
* @param messageFilter A predicate for selecting the appropriate messages
* from the server for the output stream.
*/
multiplex(subMsg: () => any, unsubMsg: () => any, messageFilter: (value: T) => boolean) {
const self = this;
return new Observable((observer: Observer<any>) => {
try {
self.next(subMsg());
} catch (err) {
observer.error(err);
}
const subscription = self.subscribe(x => {
try {
if (messageFilter(x)) {
observer.next(x);
}
} catch (err) {
observer.error(err);
}
},
err => observer.error(err),
() => observer.complete());
return () => {
try {
self.next(unsubMsg());
} catch (err) {
observer.error(err);
}
subscription.unsubscribe();
};
});
}
private _connectSocket() {
const { WebSocketCtor, protocol, url, binaryType } = this._config;
const observer = this._output;
let socket: WebSocket = null;
try {
socket = protocol ?
new WebSocketCtor(url, protocol) :
new WebSocketCtor(url);
this._socket = socket;
if (binaryType) {
this._socket.binaryType = binaryType;
}
} catch (e) {
observer.error(e);
return;
}
const subscription = new Subscription(() => {
this._socket = null;
if (socket && socket.readyState === 1) {
socket.close();
}
});
socket.onopen = (e: Event) => {
const { _socket } = this;
if (!_socket) {
socket.close();
this._resetState();
return;
}
const { openObserver } = this._config;
if (openObserver) {
openObserver.next(e);
}
const queue = this.destination;
this.destination = Subscriber.create<T>(
(x) => {
if (socket.readyState === 1) {
try {
const { serializer } = this._config;
socket.send(serializer(x));
} catch (e) {
this.destination.error(e);
}
}
},
(e) => {
const { closingObserver } = this._config;
if (closingObserver) {
closingObserver.next(undefined);
}
if (e && e.code) {
socket.close(e.code, e.reason);
} else {
observer.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT));
}
this._resetState();
},
() => {
const { closingObserver } = this._config;
if (closingObserver) {
closingObserver.next(undefined);
}
socket.close();
this._resetState();
}
) as Subscriber<any>;
if (queue && queue instanceof ReplaySubject) {
subscription.add((<ReplaySubject<T>>queue).subscribe(this.destination));
}
};
socket.onerror = (e: Event) => {
this._resetState();
observer.error(e);
};
socket.onclose = (e: CloseEvent) => {
this._resetState();
const { closeObserver } = this._config;
if (closeObserver) {
closeObserver.next(e);
}
if (e.wasClean) {
observer.complete();
} else {
observer.error(e);
}
};
socket.onmessage = (e: MessageEvent) => {
try {
const { deserializer } = this._config;
observer.next(deserializer(e));
} catch (err) {
observer.error(err);
}
};
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>): Subscription {
const { source } = this;
if (source) {
return source.subscribe(subscriber);
}
if (!this._socket) {
this._connectSocket();
}
this._output.subscribe(subscriber);
subscriber.add(() => {
const { _socket } = this;
if (this._output.observers.length === 0) {
if (_socket && _socket.readyState === 1) {
_socket.close();
}
this._resetState();
}
});
return subscriber;
}
unsubscribe() {
const { _socket } = this;
if (_socket && _socket.readyState === 1) {
_socket.close();
}
this._resetState();
super.unsubscribe();
}
}

82
node_modules/rxjs/src/internal/observable/dom/ajax.ts generated vendored Normal file
View File

@ -0,0 +1,82 @@
import { AjaxObservable, AjaxCreationMethod } from './AjaxObservable';
/**
* There is an ajax operator on the Rx object.
*
* It creates an observable for an Ajax request with either a request object with
* url, headers, etc or a string for a URL.
*
*
* ## Using ajax() to fetch the response object that is being returned from API.
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError } from 'rxjs/operators';
* import { of } from 'rxjs';
*
* const obs$ = ajax(`https://api.github.com/users?per_page=5`).pipe(
* map(userResponse => console.log('users: ', userResponse)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
*
* ```
*
* ## Using ajax.getJSON() to fetch data from API.
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError } from 'rxjs/operators';
* import { of } from 'rxjs';
*
* const obs$ = ajax.getJSON(`https://api.github.com/users?per_page=5`).pipe(
* map(userResponse => console.log('users: ', userResponse)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
*
* ```
*
* ## Using ajax() with object as argument and method POST with a two seconds delay.
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { of } from 'rxjs';
*
* const users = ajax({
* url: 'https://httpbin.org/delay/2',
* method: 'POST',
* headers: {
* 'Content-Type': 'application/json',
* 'rxjs-custom-header': 'Rxjs'
* },
* body: {
* rxjs: 'Hello World!'
* }
* }).pipe(
* map(response => console.log('response: ', response)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
*
* ```
*
* ## Using ajax() to fetch. An error object that is being returned from the request.
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError } from 'rxjs/operators';
* import { of } from 'rxjs';
*
* const obs$ = ajax(`https://api.github.com/404`).pipe(
* map(userResponse => console.log('users: ', userResponse)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
*
* ```
*/
export const ajax: AjaxCreationMethod = (() => AjaxObservable.create)();

99
node_modules/rxjs/src/internal/observable/dom/fetch.ts generated vendored Normal file
View File

@ -0,0 +1,99 @@
import { Observable } from '../../Observable';
/**
* Uses [the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to
* make an HTTP request.
*
* **WARNING** Parts of the fetch API are still experimental. `AbortController` is
* required for this implementation to work and use cancellation appropriately.
*
* Will automatically set up an internal [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)
* in order to teardown the internal `fetch` when the subscription tears down.
*
* If a `signal` is provided via the `init` argument, it will behave like it usually does with
* `fetch`. If the provided `signal` aborts, the error that `fetch` normally rejects with
* in that scenario will be emitted as an error from the observable.
*
* ### Basic Use
*
* ```ts
* import { of } from 'rxjs';
* import { fromFetch } from 'rxjs/fetch';
* import { switchMap, catchError } from 'rxjs/operators';
*
* const data$ = fromFetch('https://api.github.com/users?per_page=5').pipe(
* switchMap(response => {
* if (response.ok) {
* // OK return data
* return response.json();
* } else {
* // Server is returning a status requiring the client to try something else.
* return of({ error: true, message: `Error ${response.status}` });
* }
* }),
* catchError(err => {
* // Network or other error, handle appropriately
* console.error(err);
* return of({ error: true, message: err.message })
* })
* );
*
* data$.subscribe({
* next: result => console.log(result),
* complete: () => console.log('done')
* })
* ```
*
* @param input The resource you would like to fetch. Can be a url or a request object.
* @param init A configuration object for the fetch.
* [See MDN for more details](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
* @returns An Observable, that when subscribed to performs an HTTP request using the native `fetch`
* function. The {@link Subscription} is tied to an `AbortController` for the the fetch.
*/
export function fromFetch(input: string | Request, init?: RequestInit): Observable<Response> {
return new Observable<Response>(subscriber => {
const controller = new AbortController();
const signal = controller.signal;
let outerSignalHandler: () => void;
let abortable = true;
let unsubscribed = false;
if (init) {
// If a signal is provided, just have it teardown. It's a cancellation token, basically.
if (init.signal) {
if (init.signal.aborted) {
controller.abort();
} else {
outerSignalHandler = () => {
if (!signal.aborted) {
controller.abort();
}
};
init.signal.addEventListener('abort', outerSignalHandler);
}
}
init = { ...init, signal };
} else {
init = { signal };
}
fetch(input, init).then(response => {
abortable = false;
subscriber.next(response);
subscriber.complete();
}).catch(err => {
abortable = false;
if (!unsubscribed) {
// Only forward the error if it wasn't an abort.
subscriber.error(err);
}
});
return () => {
unsubscribed = true;
if (abortable) {
controller.abort();
}
};
});
}

View File

@ -0,0 +1,156 @@
import { WebSocketSubject, WebSocketSubjectConfig } from './WebSocketSubject';
/**
* Wrapper around the w3c-compatible WebSocket object provided by the browser.
*
* <span class="informal">{@link Subject} that communicates with a server via WebSocket</span>
*
* `webSocket` is a factory function that produces a `WebSocketSubject`,
* which can be used to make WebSocket connection with an arbitrary endpoint.
* `webSocket` accepts as an argument either a string with url of WebSocket endpoint, or an
* {@link WebSocketSubjectConfig} object for providing additional configuration, as
* well as Observers for tracking lifecycle of WebSocket connection.
*
* When `WebSocketSubject` is subscribed, it attempts to make a socket connection,
* unless there is one made already. This means that many subscribers will always listen
* on the same socket, thus saving resources. If however, two instances are made of `WebSocketSubject`,
* even if these two were provided with the same url, they will attempt to make separate
* connections. When consumer of a `WebSocketSubject` unsubscribes, socket connection is closed,
* only if there are no more subscribers still listening. If after some time a consumer starts
* subscribing again, connection is reestablished.
*
* Once connection is made, whenever a new message comes from the server, `WebSocketSubject` will emit that
* message as a value in the stream. By default, a message from the socket is parsed via `JSON.parse`. If you
* want to customize how deserialization is handled (if at all), you can provide custom `resultSelector`
* function in {@link WebSocketSubject}. When connection closes, stream will complete, provided it happened without
* any errors. If at any point (starting, maintaining or closing a connection) there is an error,
* stream will also error with whatever WebSocket API has thrown.
*
* By virtue of being a {@link Subject}, `WebSocketSubject` allows for receiving and sending messages from the server. In order
* to communicate with a connected endpoint, use `next`, `error` and `complete` methods. `next` sends a value to the server, so bear in mind
* that this value will not be serialized beforehand. Because of This, `JSON.stringify` will have to be called on a value by hand,
* before calling `next` with a result. Note also that if at the moment of nexting value
* there is no socket connection (for example no one is subscribing), those values will be buffered, and sent when connection
* is finally established. `complete` method closes socket connection. `error` does the same,
* as well as notifying the server that something went wrong via status code and string with details of what happened.
* Since status code is required in WebSocket API, `WebSocketSubject` does not allow, like regular `Subject`,
* arbitrary values being passed to the `error` method. It needs to be called with an object that has `code`
* property with status code number and optional `reason` property with string describing details
* of an error.
*
* Calling `next` does not affect subscribers of `WebSocketSubject` - they have no
* information that something was sent to the server (unless of course the server
* responds somehow to a message). On the other hand, since calling `complete` triggers
* an attempt to close socket connection. If that connection is closed without any errors, stream will
* complete, thus notifying all subscribers. And since calling `error` closes
* socket connection as well, just with a different status code for the server, if closing itself proceeds
* without errors, subscribed Observable will not error, as one might expect, but complete as usual. In both cases
* (calling `complete` or `error`), if process of closing socket connection results in some errors, *then* stream
* will error.
*
* **Multiplexing**
*
* `WebSocketSubject` has an additional operator, not found in other Subjects. It is called `multiplex` and it is
* used to simulate opening several socket connections, while in reality maintaining only one.
* For example, an application has both chat panel and real-time notifications about sport news. Since these are two distinct functions,
* it would make sense to have two separate connections for each. Perhaps there could even be two separate services with WebSocket
* endpoints, running on separate machines with only GUI combining them together. Having a socket connection
* for each functionality could become too resource expensive. It is a common pattern to have single
* WebSocket endpoint that acts as a gateway for the other services (in this case chat and sport news services).
* Even though there is a single connection in a client app, having the ability to manipulate streams as if it
* were two separate sockets is desirable. This eliminates manually registering and unregistering in a gateway for
* given service and filter out messages of interest. This is exactly what `multiplex` method is for.
*
* Method accepts three parameters. First two are functions returning subscription and unsubscription messages
* respectively. These are messages that will be sent to the server, whenever consumer of resulting Observable
* subscribes and unsubscribes. Server can use them to verify that some kind of messages should start or stop
* being forwarded to the client. In case of the above example application, after getting subscription message with proper identifier,
* gateway server can decide that it should connect to real sport news service and start forwarding messages from it.
* Note that both messages will be sent as returned by the functions, they are by default serialized using JSON.stringify, just
* as messages pushed via `next`. Also bear in mind that these messages will be sent on *every* subscription and
* unsubscription. This is potentially dangerous, because one consumer of an Observable may unsubscribe and the server
* might stop sending messages, since it got unsubscription message. This needs to be handled
* on the server or using {@link publish} on a Observable returned from 'multiplex'.
*
* Last argument to `multiplex` is a `messageFilter` function which should return a boolean. It is used to filter out messages
* sent by the server to only those that belong to simulated WebSocket stream. For example, server might mark these
* messages with some kind of string identifier on a message object and `messageFilter` would return `true`
* if there is such identifier on an object emitted by the socket. Messages which returns `false` in `messageFilter` are simply skipped,
* and are not passed down the stream.
*
* Return value of `multiplex` is an Observable with messages incoming from emulated socket connection. Note that this
* is not a `WebSocketSubject`, so calling `next` or `multiplex` again will fail. For pushing values to the
* server, use root `WebSocketSubject`.
*
* ### Examples
* #### Listening for messages from the server
* ```ts
* import { webSocket } from "rxjs/webSocket";
* const subject = webSocket("ws://localhost:8081");
*
* subject.subscribe(
* msg => console.log('message received: ' + msg), // Called whenever there is a message from the server.
* err => console.log(err), // Called if at any point WebSocket API signals some kind of error.
* () => console.log('complete') // Called when connection is closed (for whatever reason).
* );
* ```
*
* #### Pushing messages to the server
* ```ts
* import { webSocket } from "rxjs/webSocket";
* const subject = webSocket('ws://localhost:8081');
*
* subject.subscribe();
* // Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent,
* // since no connection was established!
*
* subject.next({message: 'some message'});
* // This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default!
*
* subject.complete(); // Closes the connection.
*
* subject.error({code: 4000, reason: 'I think our app just broke!'});
* // Also closes the connection, but let's the server know that this closing is caused by some error.
* ```
*
* #### Multiplexing WebSocket
* ```ts
* import { webSocket } from "rxjs/webSocket";
* const subject = webSocket('ws://localhost:8081');
*
* const observableA = subject.multiplex(
* () => ({subscribe: 'A'}), // When server gets this message, it will start sending messages for 'A'...
* () => ({unsubscribe: 'A'}), // ...and when gets this one, it will stop.
* message => message.type === 'A' // If the function returns `true` message is passed down the stream. Skipped if the function returns false.
* );
*
* const observableB = subject.multiplex( // And the same goes for 'B'.
* () => ({subscribe: 'B'}),
* () => ({unsubscribe: 'B'}),
* message => message.type === 'B'
* );
*
* const subA = observableA.subscribe(messageForA => console.log(messageForA));
* // At this moment WebSocket connection is established. Server gets '{"subscribe": "A"}' message and starts sending messages for 'A',
* // which we log here.
*
* const subB = observableB.subscribe(messageForB => console.log(messageForB));
* // Since we already have a connection, we just send '{"subscribe": "B"}' message to the server. It starts sending messages for 'B',
* // which we log here.
*
* subB.unsubscribe();
* // Message '{"unsubscribe": "B"}' is sent to the server, which stops sending 'B' messages.
*
* subA.unsubscribe();
* // Message '{"unsubscribe": "A"}' makes the server stop sending messages for 'A'. Since there is no more subscribers to root Subject,
* // socket connection closes.
* ```
*
*
* @param {string|WebSocketSubjectConfig} urlConfigOrSource The WebSocket endpoint as an url or an object with
* configuration and additional Observers.
* @return {WebSocketSubject} Subject which allows to both send and receive messages via WebSocket connection.
*/
export function webSocket<T>(urlConfigOrSource: string | WebSocketSubjectConfig<T>): WebSocketSubject<T> {
return new WebSocketSubject<T>(urlConfigOrSource);
}

68
node_modules/rxjs/src/internal/observable/empty.ts generated vendored Normal file
View File

@ -0,0 +1,68 @@
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
/**
* The same Observable instance returned by any call to {@link empty} without a
* `scheduler`. It is preferrable to use this over `empty()`.
*/
export const EMPTY = new Observable<never>(subscriber => subscriber.complete());
/**
* Creates an Observable that emits no items to the Observer and immediately
* emits a complete notification.
*
* <span class="informal">Just emits 'complete', and nothing else.
* </span>
*
* ![](empty.png)
*
* This static operator is useful for creating a simple Observable that only
* emits the complete notification. It can be used for composing with other
* Observables, such as in a {@link mergeMap}.
*
* ## Examples
* ### Emit the number 7, then complete
* ```ts
* import { empty } from 'rxjs';
* import { startWith } from 'rxjs/operators';
*
* const result = empty().pipe(startWith(7));
* result.subscribe(x => console.log(x));
* ```
*
* ### Map and flatten only odd numbers to the sequence 'a', 'b', 'c'
* ```ts
* import { empty, interval, of } from 'rxjs';
* import { mergeMap } from 'rxjs/operators';
*
* const interval$ = interval(1000);
* const result = interval$.pipe(
* mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : empty()),
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following to the console:
* // x is equal to the count on the interval eg(0,1,2,3,...)
* // x will occur every 1000ms
* // if x % 2 is equal to 1 print abc
* // if x % 2 is not equal to 1 nothing will be output
* ```
*
* @see {@link Observable}
* @see {@link never}
* @see {@link of}
* @see {@link throwError}
*
* @param scheduler A {@link SchedulerLike} to use for scheduling
* the emission of the complete notification.
* @return An "empty" Observable: emits only the complete
* notification.
* @deprecated Deprecated in favor of using {@link EMPTY} constant, or {@link scheduled} (e.g. `scheduled([], scheduler)`)
*/
export function empty(scheduler?: SchedulerLike) {
return scheduler ? emptyScheduled(scheduler) : EMPTY;
}
function emptyScheduled(scheduler: SchedulerLike) {
return new Observable<never>(subscriber => scheduler.schedule(() => subscriber.complete()));
}

204
node_modules/rxjs/src/internal/observable/forkJoin.ts generated vendored Normal file
View File

@ -0,0 +1,204 @@
import { Observable } from '../Observable';
import { ObservableInput, ObservedValuesFromArray, ObservedValueOf, SubscribableOrPromise } from '../types';
import { isArray } from '../util/isArray';
import { map } from '../operators/map';
import { isObject } from '../util/isObject';
import { isObservable } from '../util/isObservable';
import { from } from './from';
/* tslint:disable:max-line-length */
// forkJoin(a$, b$, c$)
/** @deprecated Use the version that takes an array of Observables instead */
export function forkJoin<T>(v1: SubscribableOrPromise<T>): Observable<[T]>;
/** @deprecated Use the version that takes an array of Observables instead */
export function forkJoin<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>): Observable<[T, T2]>;
/** @deprecated Use the version that takes an array of Observables instead */
export function forkJoin<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<[T, T2, T3]>;
/** @deprecated Use the version that takes an array of Observables instead */
export function forkJoin<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<[T, T2, T3, T4]>;
/** @deprecated Use the version that takes an array of Observables instead */
export function forkJoin<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<[T, T2, T3, T4, T5]>;
/** @deprecated Use the version that takes an array of Observables instead */
export function forkJoin<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<[T, T2, T3, T4, T5, T6]>;
// forkJoin([a$, b$, c$]);
// TODO(benlesh): Uncomment for TS 3.0
// export function forkJoin(sources: []): Observable<never>;
export function forkJoin<A>(sources: [ObservableInput<A>]): Observable<[A]>;
export function forkJoin<A, B>(sources: [ObservableInput<A>, ObservableInput<B>]): Observable<[A, B]>;
export function forkJoin<A, B, C>(sources: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>]): Observable<[A, B, C]>;
export function forkJoin<A, B, C, D>(sources: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>]): Observable<[A, B, C, D]>;
export function forkJoin<A, B, C, D, E>(sources: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>, ObservableInput<E>]): Observable<[A, B, C, D, E]>;
export function forkJoin<A, B, C, D, E, F>(sources: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>, ObservableInput<E>, ObservableInput<F>]): Observable<[A, B, C, D, E, F]>;
export function forkJoin<A extends ObservableInput<any>[]>(sources: A): Observable<ObservedValuesFromArray<A>[]>;
// forkJoin({})
export function forkJoin(sourcesObject: {}): Observable<never>;
export function forkJoin<T, K extends keyof T>(sourcesObject: T): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;
/** @deprecated resultSelector is deprecated, pipe to map instead */
export function forkJoin(...args: Array<ObservableInput<any>|Function>): Observable<any>;
/** @deprecated Use the version that takes an array of Observables instead */
export function forkJoin<T>(...sources: ObservableInput<T>[]): Observable<T[]>;
/* tslint:enable:max-line-length */
/**
* Accepts an `Array` of {@link ObservableInput} or a dictionary `Object` of {@link ObservableInput} and returns
* an {@link Observable} that emits either an array of values in the exact same order as the passed array,
* or a dictionary of values in the same shape as the passed dictionary.
*
* <span class="informal">Wait for Observables to complete and then combine last values they emitted.</span>
*
* ![](forkJoin.png)
*
* `forkJoin` is an operator that takes any number of input observables which can be passed either as an array
* or a dictionary of input observables. If no input observables are provided, resulting stream will complete
* immediately.
*
* `forkJoin` will wait for all passed observables to complete and then it will emit an array or an object with last
* values from corresponding observables.
*
* If you pass an array of `n` observables to the operator, resulting
* array will have `n` values, where first value is the last thing emitted by the first observable,
* second value is the last thing emitted by the second observable and so on.
*
* If you pass a dictionary of observables to the operator, resulting
* objects will have the same keys as the dictionary passed, with their last values they've emitted
* located at the corresponding key.
*
* That means `forkJoin` will not emit more than once and it will complete after that. If you need to emit combined
* values not only at the end of lifecycle of passed observables, but also throughout it, try out {@link combineLatest}
* or {@link zip} instead.
*
* In order for resulting array to have the same length as the number of input observables, whenever any of
* that observables completes without emitting any value, `forkJoin` will complete at that moment as well
* and it will not emit anything either, even if it already has some last values from other observables.
* Conversely, if there is an observable that never completes, `forkJoin` will never complete as well,
* unless at any point some other observable completes without emitting value, which brings us back to
* the previous case. Overall, in order for `forkJoin` to emit a value, all observables passed as arguments
* have to emit something at least once and complete.
*
* If any input observable errors at some point, `forkJoin` will error as well and all other observables
* will be immediately unsubscribed.
*
* Optionally `forkJoin` accepts project function, that will be called with values which normally
* would land in emitted array. Whatever is returned by project function, will appear in output
* observable instead. This means that default project can be thought of as a function that takes
* all its arguments and puts them into an array. Note that project function will be called only
* when output observable is supposed to emit a result.
*
* ## Examples
*
* ### Use forkJoin with a dictionary of observable inputs
* ```ts
* import { forkJoin, of, timer } from 'rxjs';
*
* const observable = forkJoin({
* foo: of(1, 2, 3, 4),
* bar: Promise.resolve(8),
* baz: timer(4000),
* });
* observable.subscribe({
* next: value => console.log(value),
* complete: () => console.log('This is how it ends!'),
* });
*
* // Logs:
* // { foo: 4, bar: 8, baz: 0 } after 4 seconds
* // "This is how it ends!" immediately after
* ```
*
* ### Use forkJoin with an array of observable inputs
* ```ts
* import { forkJoin, of } from 'rxjs';
*
* const observable = forkJoin([
* of(1, 2, 3, 4),
* Promise.resolve(8),
* timer(4000),
* ]);
* observable.subscribe({
* next: value => console.log(value),
* complete: () => console.log('This is how it ends!'),
* });
*
* // Logs:
* // [4, 8, 0] after 4 seconds
* // "This is how it ends!" immediately after
* ```
*
* @see {@link combineLatest}
* @see {@link zip}
*
* @param {...ObservableInput} sources Any number of Observables provided either as an array or as an arguments
* passed directly to the operator.
* @param {function} [project] Function that takes values emitted by input Observables and returns value
* that will appear in resulting Observable instead of default array.
* @return {Observable} Observable emitting either an array of last values emitted by passed Observables
* or value from project function.
*/
export function forkJoin(
...sources: any[]
): Observable<any> {
if (sources.length === 1) {
const first = sources[0];
if (isArray(first)) {
return forkJoinInternal(first, null);
}
// TODO(benlesh): isObservable check will not be necessary when deprecated path is removed.
if (isObject(first) && Object.getPrototypeOf(first) === Object.prototype) {
const keys = Object.keys(first);
return forkJoinInternal(keys.map(key => first[key]), keys);
}
}
// DEPRECATED PATHS BELOW HERE
if (typeof sources[sources.length - 1] === 'function') {
const resultSelector = sources.pop() as Function;
sources = (sources.length === 1 && isArray(sources[0])) ? sources[0] : sources;
return forkJoinInternal(sources, null).pipe(
map((args: any[]) => resultSelector(...args))
);
}
return forkJoinInternal(sources, null);
}
function forkJoinInternal(sources: ObservableInput<any>[], keys: string[] | null): Observable<any> {
return new Observable(subscriber => {
const len = sources.length;
if (len === 0) {
subscriber.complete();
return;
}
const values = new Array(len);
let completed = 0;
let emitted = 0;
for (let i = 0; i < len; i++) {
const source = from(sources[i]);
let hasValue = false;
subscriber.add(source.subscribe({
next: value => {
if (!hasValue) {
hasValue = true;
emitted++;
}
values[i] = value;
},
error: err => subscriber.error(err),
complete: () => {
completed++;
if (completed === len || !hasValue) {
if (emitted === len) {
subscriber.next(keys ?
keys.reduce((result, key, i) => (result[key] = values[i], result), {}) :
values);
}
subscriber.complete();
}
}
}));
}
});
}

118
node_modules/rxjs/src/internal/observable/from.ts generated vendored Normal file
View File

@ -0,0 +1,118 @@
import { Observable } from '../Observable';
import { subscribeTo } from '../util/subscribeTo';
import { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';
import { scheduled } from '../scheduled/scheduled';
export function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;
/** @deprecated use {@link scheduled} instead. */
export function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike): Observable<ObservedValueOf<O>>;
/**
* Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.
*
* <span class="informal">Converts almost anything to an Observable.</span>
*
* ![](from.png)
*
* `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable" target="_blank">iterable</a>
* object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated
* as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be
* converted through this operator.
*
* ## Examples
*
* ### Converts an array to an Observable
*
* ```ts
* import { from } from 'rxjs';
*
* const array = [10, 20, 30];
* const result = from(array);
*
* result.subscribe(x => console.log(x));
*
* // Logs:
* // 10
* // 20
* // 30
* ```
*
* ---
*
* ### Convert an infinite iterable (from a generator) to an Observable
*
* ```ts
* import { from } from 'rxjs';
* import { take } from 'rxjs/operators';
*
* function* generateDoubles(seed) {
* let i = seed;
* while (true) {
* yield i;
* i = 2 * i; // double it
* }
* }
*
* const iterator = generateDoubles(3);
* const result = from(iterator).pipe(take(10));
*
* result.subscribe(x => console.log(x));
*
* // Logs:
* // 3
* // 6
* // 12
* // 24
* // 48
* // 96
* // 192
* // 384
* // 768
* // 1536
* ```
*
* ---
*
* ### With async scheduler
*
* ```ts
* import { from, asyncScheduler } from 'rxjs';
*
* console.log('start');
*
* const array = [10, 20, 30];
* const result = from(array, asyncScheduler);
*
* result.subscribe(x => console.log(x));
*
* console.log('end');
*
* // Logs:
* // start
* // end
* // 10
* // 20
* // 30
* ```
*
* @see {@link fromEvent}
* @see {@link fromEventPattern}
*
* @param {ObservableInput<T>} A subscription object, a Promise, an Observable-like,
* an Array, an iterable, or an array-like object to be converted.
* @param {SchedulerLike} An optional {@link SchedulerLike} on which to schedule the emission of values.
* @return {Observable<T>}
* @name from
* @owner Observable
*/
export function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {
if (!scheduler) {
if (input instanceof Observable) {
return input;
}
return new Observable<T>(subscribeTo(input));
} else {
return scheduled(input, scheduler);
}
}

12
node_modules/rxjs/src/internal/observable/fromArray.ts generated vendored Normal file
View File

@ -0,0 +1,12 @@
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
import { subscribeToArray } from '../util/subscribeToArray';
import { scheduleArray } from '../scheduled/scheduleArray';
export function fromArray<T>(input: ArrayLike<T>, scheduler?: SchedulerLike) {
if (!scheduler) {
return new Observable<T>(subscribeToArray(input));
} else {
return scheduleArray(input, scheduler);
}
}

245
node_modules/rxjs/src/internal/observable/fromEvent.ts generated vendored Normal file
View File

@ -0,0 +1,245 @@
import { Observable } from '../Observable';
import { isArray } from '../util/isArray';
import { isFunction } from '../util/isFunction';
import { Subscriber } from '../Subscriber';
import { map } from '../operators/map';
const toString: Function = (() => Object.prototype.toString)();
export interface NodeStyleEventEmitter {
addListener: (eventName: string | symbol, handler: NodeEventHandler) => this;
removeListener: (eventName: string | symbol, handler: NodeEventHandler) => this;
}
export type NodeEventHandler = (...args: any[]) => void;
// For APIs that implement `addListener` and `removeListener` methods that may
// not use the same arguments or return EventEmitter values
// such as React Native
export interface NodeCompatibleEventEmitter {
addListener: (eventName: string, handler: NodeEventHandler) => void | {};
removeListener: (eventName: string, handler: NodeEventHandler) => void | {};
}
export interface JQueryStyleEventEmitter {
on: (eventName: string, handler: Function) => void;
off: (eventName: string, handler: Function) => void;
}
export interface HasEventTargetAddRemove<E> {
addEventListener(type: string, listener: ((evt: E) => void) | null, options?: boolean | AddEventListenerOptions): void;
removeEventListener(type: string, listener?: ((evt: E) => void) | null, options?: EventListenerOptions | boolean): void;
}
export type EventTargetLike<T> = HasEventTargetAddRemove<T> | NodeStyleEventEmitter | NodeCompatibleEventEmitter | JQueryStyleEventEmitter;
export type FromEventTarget<T> = EventTargetLike<T> | ArrayLike<EventTargetLike<T>>;
export interface EventListenerOptions {
capture?: boolean;
passive?: boolean;
once?: boolean;
}
export interface AddEventListenerOptions extends EventListenerOptions {
once?: boolean;
passive?: boolean;
}
/* tslint:disable:max-line-length */
export function fromEvent<T>(target: FromEventTarget<T>, eventName: string): Observable<T>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function fromEvent<T>(target: FromEventTarget<T>, eventName: string, resultSelector: (...args: any[]) => T): Observable<T>;
export function fromEvent<T>(target: FromEventTarget<T>, eventName: string, options: EventListenerOptions): Observable<T>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function fromEvent<T>(target: FromEventTarget<T>, eventName: string, options: EventListenerOptions, resultSelector: (...args: any[]) => T): Observable<T>;
/* tslint:enable:max-line-length */
/**
* Creates an Observable that emits events of a specific type coming from the
* given event target.
*
* <span class="informal">Creates an Observable from DOM events, or Node.js
* EventEmitter events or others.</span>
*
* ![](fromEvent.png)
*
* `fromEvent` accepts as a first argument event target, which is an object with methods
* for registering event handler functions. As a second argument it takes string that indicates
* type of event we want to listen for. `fromEvent` supports selected types of event targets,
* which are described in detail below. If your event target does not match any of the ones listed,
* you should use {@link fromEventPattern}, which can be used on arbitrary APIs.
* When it comes to APIs supported by `fromEvent`, their methods for adding and removing event
* handler functions have different names, but they all accept a string describing event type
* and function itself, which will be called whenever said event happens.
*
* Every time resulting Observable is subscribed, event handler function will be registered
* to event target on given event type. When that event fires, value
* passed as a first argument to registered function will be emitted by output Observable.
* When Observable is unsubscribed, function will be unregistered from event target.
*
* Note that if event target calls registered function with more than one argument, second
* and following arguments will not appear in resulting stream. In order to get access to them,
* you can pass to `fromEvent` optional project function, which will be called with all arguments
* passed to event handler. Output Observable will then emit value returned by project function,
* instead of the usual value.
*
* Remember that event targets listed below are checked via duck typing. It means that
* no matter what kind of object you have and no matter what environment you work in,
* you can safely use `fromEvent` on that object if it exposes described methods (provided
* of course they behave as was described above). So for example if Node.js library exposes
* event target which has the same method names as DOM EventTarget, `fromEvent` is still
* a good choice.
*
* If the API you use is more callback then event handler oriented (subscribed
* callback function fires only once and thus there is no need to manually
* unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}
* instead.
*
* `fromEvent` supports following types of event targets:
*
* **DOM EventTarget**
*
* This is an object with `addEventListener` and `removeEventListener` methods.
*
* In the browser, `addEventListener` accepts - apart from event type string and event
* handler function arguments - optional third parameter, which is either an object or boolean,
* both used for additional configuration how and when passed function will be called. When
* `fromEvent` is used with event target of that type, you can provide this values
* as third parameter as well.
*
* **Node.js EventEmitter**
*
* An object with `addListener` and `removeListener` methods.
*
* **JQuery-style event target**
*
* An object with `on` and `off` methods
*
* **DOM NodeList**
*
* List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.
*
* Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes
* it contains and install event handler function in every of them. When returned Observable
* is unsubscribed, function will be removed from all Nodes.
*
* **DOM HtmlCollection**
*
* Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is
* installed and removed in each of elements.
*
*
* ## Examples
* ### Emits clicks happening on the DOM document
* ```ts
* import { fromEvent } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* clicks.subscribe(x => console.log(x));
*
* // Results in:
* // MouseEvent object logged to console every time a click
* // occurs on the document.
* ```
*
* ### Use addEventListener with capture option
* ```ts
* import { fromEvent } from 'rxjs';
*
* const clicksInDocument = fromEvent(document, 'click', true); // note optional configuration parameter
* // which will be passed to addEventListener
* const clicksInDiv = fromEvent(someDivInDocument, 'click');
*
* clicksInDocument.subscribe(() => console.log('document'));
* clicksInDiv.subscribe(() => console.log('div'));
*
* // By default events bubble UP in DOM tree, so normally
* // when we would click on div in document
* // "div" would be logged first and then "document".
* // Since we specified optional `capture` option, document
* // will catch event when it goes DOWN DOM tree, so console
* // will log "document" and then "div".
* ```
*
* @see {@link bindCallback}
* @see {@link bindNodeCallback}
* @see {@link fromEventPattern}
*
* @param {FromEventTarget<T>} target The DOM EventTarget, Node.js
* EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.
* @param {string} eventName The event name of interest, being emitted by the
* `target`.
* @param {EventListenerOptions} [options] Options to pass through to addEventListener
* @return {Observable<T>}
* @name fromEvent
*/
export function fromEvent<T>(
target: FromEventTarget<T>,
eventName: string,
options?: EventListenerOptions | ((...args: any[]) => T),
resultSelector?: ((...args: any[]) => T)
): Observable<T> {
if (isFunction(options)) {
// DEPRECATED PATH
resultSelector = options;
options = undefined;
}
if (resultSelector) {
// DEPRECATED PATH
return fromEvent<T>(target, eventName, <EventListenerOptions | undefined>options).pipe(
map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))
);
}
return new Observable<T>(subscriber => {
function handler(e: T) {
if (arguments.length > 1) {
subscriber.next(Array.prototype.slice.call(arguments));
} else {
subscriber.next(e);
}
}
setupSubscription(target, eventName, handler, subscriber, options as EventListenerOptions);
});
}
function setupSubscription<T>(sourceObj: FromEventTarget<T>, eventName: string,
handler: (...args: any[]) => void, subscriber: Subscriber<T>,
options?: EventListenerOptions) {
let unsubscribe: () => void;
if (isEventTarget(sourceObj)) {
const source = sourceObj;
sourceObj.addEventListener(eventName, handler, options);
unsubscribe = () => source.removeEventListener(eventName, handler, options);
} else if (isJQueryStyleEventEmitter(sourceObj)) {
const source = sourceObj;
sourceObj.on(eventName, handler);
unsubscribe = () => source.off(eventName, handler);
} else if (isNodeStyleEventEmitter(sourceObj)) {
const source = sourceObj;
sourceObj.addListener(eventName, handler as NodeEventHandler);
unsubscribe = () => source.removeListener(eventName, handler as NodeEventHandler);
} else if (sourceObj && (sourceObj as any).length) {
for (let i = 0, len = (sourceObj as any).length; i < len; i++) {
setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
}
} else {
throw new TypeError('Invalid event target');
}
subscriber.add(unsubscribe);
}
function isNodeStyleEventEmitter(sourceObj: any): sourceObj is NodeStyleEventEmitter {
return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
}
function isJQueryStyleEventEmitter(sourceObj: any): sourceObj is JQueryStyleEventEmitter {
return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
}
function isEventTarget(sourceObj: any): sourceObj is HasEventTargetAddRemove<any> {
return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
}

View File

@ -0,0 +1,169 @@
import { Observable } from '../Observable';
import { isArray } from '../util/isArray';
import { isFunction } from '../util/isFunction';
import { NodeEventHandler } from './fromEvent';
import { map } from '../operators/map';
/* tslint:disable:max-line-length */
export function fromEventPattern<T>(addHandler: (handler: NodeEventHandler) => any, removeHandler?: (handler: NodeEventHandler, signal?: any) => void): Observable<T>;
/** @deprecated resultSelector no longer supported, pipe to map instead */
export function fromEventPattern<T>(addHandler: (handler: NodeEventHandler) => any, removeHandler?: (handler: NodeEventHandler, signal?: any) => void, resultSelector?: (...args: any[]) => T): Observable<T>;
/* tslint:enable:max-line-length */
/**
* Creates an Observable from an arbitrary API for registering event handlers.
*
* <span class="informal">When that method for adding event handler was something {@link fromEvent}
* was not prepared for.</span>
*
* ![](fromEventPattern.png)
*
* `fromEventPattern` allows you to convert into an Observable any API that supports registering handler functions
* for events. It is similar to {@link fromEvent}, but far
* more flexible. In fact, all use cases of {@link fromEvent} could be easily handled by
* `fromEventPattern` (although in slightly more verbose way).
*
* This operator accepts as a first argument an `addHandler` function, which will be injected with
* handler parameter. That handler is actually an event handler function that you now can pass
* to API expecting it. `addHandler` will be called whenever Observable
* returned by the operator is subscribed, so registering handler in API will not
* necessarily happen when `fromEventPattern` is called.
*
* After registration, every time an event that we listen to happens,
* Observable returned by `fromEventPattern` will emit value that event handler
* function was called with. Note that if event handler was called with more
* then one argument, second and following arguments will not appear in the Observable.
*
* If API you are using allows to unregister event handlers as well, you can pass to `fromEventPattern`
* another function - `removeHandler` - as a second parameter. It will be injected
* with the same handler function as before, which now you can use to unregister
* it from the API. `removeHandler` will be called when consumer of resulting Observable
* unsubscribes from it.
*
* In some APIs unregistering is actually handled differently. Method registering an event handler
* returns some kind of token, which is later used to identify which function should
* be unregistered or it itself has method that unregisters event handler.
* If that is the case with your API, make sure token returned
* by registering method is returned by `addHandler`. Then it will be passed
* as a second argument to `removeHandler`, where you will be able to use it.
*
* If you need access to all event handler parameters (not only the first one),
* or you need to transform them in any way, you can call `fromEventPattern` with optional
* third parameter - project function which will accept all arguments passed to
* event handler when it is called. Whatever is returned from project function will appear on
* resulting stream instead of usual event handlers first argument. This means
* that default project can be thought of as function that takes its first parameter
* and ignores the rest.
*
* ## Example
* ### Emits clicks happening on the DOM document
*
* ```ts
* import { fromEventPattern } from 'rxjs';
*
* function addClickHandler(handler) {
* document.addEventListener('click', handler);
* }
*
* function removeClickHandler(handler) {
* document.removeEventListener('click', handler);
* }
*
* const clicks = fromEventPattern(
* addClickHandler,
* removeClickHandler
* );
* clicks.subscribe(x => console.log(x));
*
* // Whenever you click anywhere in the browser, DOM MouseEvent
* // object will be logged.
* ```
*
* ## Example
* ### Use with API that returns cancellation token
*
* ```ts
* import { fromEventPattern } from 'rxjs';
*
* const token = someAPI.registerEventHandler(function() {});
* someAPI.unregisterEventHandler(token); // this APIs cancellation method accepts
* // not handler itself, but special token.
*
* const someAPIObservable = fromEventPattern(
* function(handler) { return someAPI.registerEventHandler(handler); }, // Note that we return the token here...
* function(handler, token) { someAPI.unregisterEventHandler(token); } // ...to then use it here.
* );
* ```
*
* ## Example
* ### Use with project function
*
* ```ts
* import { fromEventPattern } from 'rxjs';
*
* someAPI.registerEventHandler((eventType, eventMessage) => {
* console.log(eventType, eventMessage); // Logs "EVENT_TYPE" "EVENT_MESSAGE" to console.
* });
*
* const someAPIObservable = fromEventPattern(
* handler => someAPI.registerEventHandler(handler),
* handler => someAPI.unregisterEventHandler(handler)
* (eventType, eventMessage) => eventType + " --- " + eventMessage // without that function only "EVENT_TYPE"
* ); // would be emitted by the Observable
*
* someAPIObservable.subscribe(value => console.log(value));
*
* // Logs:
* // "EVENT_TYPE --- EVENT_MESSAGE"
* ```
*
* @see {@link fromEvent}
* @see {@link bindCallback}
* @see {@link bindNodeCallback}
*
* @param {function(handler: Function): any} addHandler A function that takes
* a `handler` function as argument and attaches it somehow to the actual
* source of events.
* @param {function(handler: Function, token?: any): void} [removeHandler] A function that
* takes a `handler` function as an argument and removes it from the event source. If `addHandler`
* returns some kind of token, `removeHandler` function will have it as a second parameter.
* @param {function(...args: any): T} [project] A function to
* transform results. It takes the arguments from the event handler and
* should return a single value.
* @return {Observable<T>} Observable which, when an event happens, emits first parameter
* passed to registered event handler. Alternatively it emits whatever project function returns
* at that moment.
* @static true
* @name fromEventPattern
* @owner Observable
*/
export function fromEventPattern<T>(addHandler: (handler: NodeEventHandler) => any,
removeHandler?: (handler: NodeEventHandler, signal?: any) => void,
resultSelector?: (...args: any[]) => T): Observable<T | T[]> {
if (resultSelector) {
// DEPRECATED PATH
return fromEventPattern<T>(addHandler, removeHandler).pipe(
map(args => isArray(args) ? resultSelector(...args) : resultSelector(args))
);
}
return new Observable<T | T[]>(subscriber => {
const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e);
let retValue: any;
try {
retValue = addHandler(handler);
} catch (err) {
subscriber.error(err);
return undefined;
}
if (!isFunction(removeHandler)) {
return undefined;
}
return () => removeHandler(handler, retValue) ;
});
}

View File

@ -0,0 +1,15 @@
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
import { subscribeToIterable } from '../util/subscribeToIterable';
import { scheduleIterable } from '../scheduled/scheduleIterable';
export function fromIterable<T>(input: Iterable<T>, scheduler?: SchedulerLike) {
if (!input) {
throw new Error('Iterable cannot be null');
}
if (!scheduler) {
return new Observable<T>(subscribeToIterable(input));
} else {
return scheduleIterable(input, scheduler);
}
}

View File

@ -0,0 +1,12 @@
import { Observable } from '../Observable';
import { subscribeToObservable } from '../util/subscribeToObservable';
import { InteropObservable, SchedulerLike } from '../types';
import { scheduleObservable } from '../scheduled/scheduleObservable';
export function fromObservable<T>(input: InteropObservable<T>, scheduler?: SchedulerLike) {
if (!scheduler) {
return new Observable<T>(subscribeToObservable(input));
} else {
return scheduleObservable(input, scheduler);
}
}

View File

@ -0,0 +1,12 @@
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
import { subscribeToPromise } from '../util/subscribeToPromise';
import { schedulePromise } from '../scheduled/schedulePromise';
export function fromPromise<T>(input: PromiseLike<T>, scheduler?: SchedulerLike) {
if (!scheduler) {
return new Observable<T>(subscribeToPromise(input));
} else {
return schedulePromise(input, scheduler);
}
}

379
node_modules/rxjs/src/internal/observable/generate.ts generated vendored Normal file
View File

@ -0,0 +1,379 @@
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { identity } from '../util/identity';
import { SchedulerAction, SchedulerLike } from '../types';
import { isScheduler } from '../util/isScheduler';
export type ConditionFunc<S> = (state: S) => boolean;
export type IterateFunc<S> = (state: S) => S;
export type ResultFunc<S, T> = (state: S) => T;
interface SchedulerState<T, S> {
needIterate?: boolean;
state: S;
subscriber: Subscriber<T>;
condition?: ConditionFunc<S>;
iterate: IterateFunc<S>;
resultSelector: ResultFunc<S, T>;
}
export interface GenerateBaseOptions<S> {
/**
* Initial state.
*/
initialState: S;
/**
* Condition function that accepts state and returns boolean.
* When it returns false, the generator stops.
* If not specified, a generator never stops.
*/
condition?: ConditionFunc<S>;
/**
* Iterate function that accepts state and returns new state.
*/
iterate: IterateFunc<S>;
/**
* SchedulerLike to use for generation process.
* By default, a generator starts immediately.
*/
scheduler?: SchedulerLike;
}
export interface GenerateOptions<T, S> extends GenerateBaseOptions<S> {
/**
* Result selection function that accepts state and returns a value to emit.
*/
resultSelector: ResultFunc<S, T>;
}
/**
* Generates an observable sequence by running a state-driven loop
* producing the sequence's elements, using the specified scheduler
* to send out observer messages.
*
* ![](generate.png)
*
* @example <caption>Produces sequence of 0, 1, 2, ... 9, then completes.</caption>
* const res = generate(0, x => x < 10, x => x + 1, x => x);
*
* @example <caption>Using asap scheduler, produces sequence of 2, 3, 5, then completes.</caption>
* const res = generate(1, x => x < 5, x => x * 2, x => x + 1, asap);
*
* @see {@link from}
* @see {@link Observable}
*
* @param {S} initialState Initial state.
* @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false).
* @param {function (state: S): S} iterate Iteration step function.
* @param {function (state: S): T} resultSelector Selector function for results produced in the sequence. (deprecated)
* @param {SchedulerLike} [scheduler] A {@link SchedulerLike} on which to run the generator loop. If not provided, defaults to emit immediately.
* @returns {Observable<T>} The generated sequence.
*/
export function generate<T, S>(initialState: S,
condition: ConditionFunc<S>,
iterate: IterateFunc<S>,
resultSelector: ResultFunc<S, T>,
scheduler?: SchedulerLike): Observable<T>;
/**
* Generates an Observable by running a state-driven loop
* that emits an element on each iteration.
*
* <span class="informal">Use it instead of nexting values in a for loop.</span>
*
* <img src="./img/generate.png" width="100%">
*
* `generate` allows you to create stream of values generated with a loop very similar to
* traditional for loop. First argument of `generate` is a beginning value. Second argument
* is a function that accepts this value and tests if some condition still holds. If it does,
* loop continues, if not, it stops. Third value is a function which takes previously defined
* value and modifies it in some way on each iteration. Note how these three parameters
* are direct equivalents of three expressions in regular for loop: first expression
* initializes some state (for example numeric index), second tests if loop can make next
* iteration (for example if index is lower than 10) and third states how defined value
* will be modified on every step (index will be incremented by one).
*
* Return value of a `generate` operator is an Observable that on each loop iteration
* emits a value. First, condition function is ran. If it returned true, Observable
* emits currently stored value (initial value at the first iteration) and then updates
* that value with iterate function. If at some point condition returned false, Observable
* completes at that moment.
*
* Optionally you can pass fourth parameter to `generate` - a result selector function which allows you
* to immediately map value that would normally be emitted by an Observable.
*
* If you find three anonymous functions in `generate` call hard to read, you can provide
* single object to the operator instead. That object has properties: `initialState`,
* `condition`, `iterate` and `resultSelector`, which should have respective values that you
* would normally pass to `generate`. `resultSelector` is still optional, but that form
* of calling `generate` allows you to omit `condition` as well. If you omit it, that means
* condition always holds, so output Observable will never complete.
*
* Both forms of `generate` can optionally accept a scheduler. In case of multi-parameter call,
* scheduler simply comes as a last argument (no matter if there is resultSelector
* function or not). In case of single-parameter call, you can provide it as a
* `scheduler` property on object passed to the operator. In both cases scheduler decides when
* next iteration of the loop will happen and therefore when next value will be emitted
* by the Observable. For example to ensure that each value is pushed to the observer
* on separate task in event loop, you could use `async` scheduler. Note that
* by default (when no scheduler is passed) values are simply emitted synchronously.
*
*
* @example <caption>Use with condition and iterate functions.</caption>
* const generated = generate(0, x => x < 3, x => x + 1);
*
* generated.subscribe(
* value => console.log(value),
* err => {},
* () => console.log('Yo!')
* );
*
* // Logs:
* // 0
* // 1
* // 2
* // "Yo!"
*
*
* @example <caption>Use with condition, iterate and resultSelector functions.</caption>
* const generated = generate(0, x => x < 3, x => x + 1, x => x * 1000);
*
* generated.subscribe(
* value => console.log(value),
* err => {},
* () => console.log('Yo!')
* );
*
* // Logs:
* // 0
* // 1000
* // 2000
* // "Yo!"
*
*
* @example <caption>Use with options object.</caption>
* const generated = generate({
* initialState: 0,
* condition(value) { return value < 3; },
* iterate(value) { return value + 1; },
* resultSelector(value) { return value * 1000; }
* });
*
* generated.subscribe(
* value => console.log(value),
* err => {},
* () => console.log('Yo!')
* );
*
* // Logs:
* // 0
* // 1000
* // 2000
* // "Yo!"
*
* @example <caption>Use options object without condition function.</caption>
* const generated = generate({
* initialState: 0,
* iterate(value) { return value + 1; },
* resultSelector(value) { return value * 1000; }
* });
*
* generated.subscribe(
* value => console.log(value),
* err => {},
* () => console.log('Yo!') // This will never run.
* );
*
* // Logs:
* // 0
* // 1000
* // 2000
* // 3000
* // ...and never stops.
*
*
* @see {@link from}
* @see {@link index/Observable.create}
*
* @param {S} initialState Initial state.
* @param {function (state: S): boolean} condition Condition to terminate generation (upon returning false).
* @param {function (state: S): S} iterate Iteration step function.
* @param {function (state: S): T} [resultSelector] Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] A {@link Scheduler} on which to run the generator loop. If not provided, defaults to emitting immediately.
* @return {Observable<T>} The generated sequence.
*/
export function generate<S>(initialState: S,
condition: ConditionFunc<S>,
iterate: IterateFunc<S>,
scheduler?: SchedulerLike): Observable<S>;
/**
* Generates an observable sequence by running a state-driven loop
* producing the sequence's elements, using the specified scheduler
* to send out observer messages.
* The overload accepts options object that might contain initial state, iterate,
* condition and scheduler.
*
* ![](generate.png)
*
* @example <caption>Produces sequence of 0, 1, 2, ... 9, then completes.</caption>
* const res = generate({
* initialState: 0,
* condition: x => x < 10,
* iterate: x => x + 1,
* });
*
* @see {@link from}
* @see {@link Observable}
*
* @param {GenerateBaseOptions<S>} options Object that must contain initialState, iterate and might contain condition and scheduler.
* @returns {Observable<S>} The generated sequence.
*/
export function generate<S>(options: GenerateBaseOptions<S>): Observable<S>;
/**
* Generates an observable sequence by running a state-driven loop
* producing the sequence's elements, using the specified scheduler
* to send out observer messages.
* The overload accepts options object that might contain initial state, iterate,
* condition, result selector and scheduler.
*
* ![](generate.png)
*
* @example <caption>Produces sequence of 0, 1, 2, ... 9, then completes.</caption>
* const res = generate({
* initialState: 0,
* condition: x => x < 10,
* iterate: x => x + 1,
* resultSelector: x => x,
* });
*
* @see {@link from}
* @see {@link Observable}
*
* @param {GenerateOptions<T, S>} options Object that must contain initialState, iterate, resultSelector and might contain condition and scheduler.
* @returns {Observable<T>} The generated sequence.
*/
export function generate<T, S>(options: GenerateOptions<T, S>): Observable<T>;
export function generate<T, S>(initialStateOrOptions: S | GenerateOptions<T, S>,
condition?: ConditionFunc<S>,
iterate?: IterateFunc<S>,
resultSelectorOrObservable?: (ResultFunc<S, T>) | SchedulerLike,
scheduler?: SchedulerLike): Observable<T> {
let resultSelector: ResultFunc<S, T>;
let initialState: S;
if (arguments.length == 1) {
const options = initialStateOrOptions as GenerateOptions<T, S>;
initialState = options.initialState;
condition = options.condition;
iterate = options.iterate;
resultSelector = options.resultSelector || identity as ResultFunc<S, T>;
scheduler = options.scheduler;
} else if (resultSelectorOrObservable === undefined || isScheduler(resultSelectorOrObservable)) {
initialState = initialStateOrOptions as S;
resultSelector = identity as ResultFunc<S, T>;
scheduler = resultSelectorOrObservable as SchedulerLike;
} else {
initialState = initialStateOrOptions as S;
resultSelector = resultSelectorOrObservable as ResultFunc<S, T>;
}
return new Observable<T>(subscriber => {
let state = initialState;
if (scheduler) {
return scheduler.schedule<SchedulerState<T, S>>(dispatch, 0, {
subscriber,
iterate,
condition,
resultSelector,
state
});
}
do {
if (condition) {
let conditionResult: boolean;
try {
conditionResult = condition(state);
} catch (err) {
subscriber.error(err);
return undefined;
}
if (!conditionResult) {
subscriber.complete();
break;
}
}
let value: T;
try {
value = resultSelector(state);
} catch (err) {
subscriber.error(err);
return undefined;
}
subscriber.next(value);
if (subscriber.closed) {
break;
}
try {
state = iterate(state);
} catch (err) {
subscriber.error(err);
return undefined;
}
} while (true);
return undefined;
});
}
function dispatch<T, S>(this: SchedulerAction<SchedulerState<T, S>>, state: SchedulerState<T, S>) {
const { subscriber, condition } = state;
if (subscriber.closed) {
return undefined;
}
if (state.needIterate) {
try {
state.state = state.iterate(state.state);
} catch (err) {
subscriber.error(err);
return undefined;
}
} else {
state.needIterate = true;
}
if (condition) {
let conditionResult: boolean;
try {
conditionResult = condition(state.state);
} catch (err) {
subscriber.error(err);
return undefined;
}
if (!conditionResult) {
subscriber.complete();
return undefined;
}
if (subscriber.closed) {
return undefined;
}
}
let value: T;
try {
value = state.resultSelector(state.state);
} catch (err) {
subscriber.error(err);
return undefined;
}
if (subscriber.closed) {
return undefined;
}
subscriber.next(value);
if (subscriber.closed) {
return undefined;
}
return this.schedule(state);
}

100
node_modules/rxjs/src/internal/observable/iif.ts generated vendored Normal file
View File

@ -0,0 +1,100 @@
import { Observable } from '../Observable';
import { defer } from './defer';
import { EMPTY } from './empty';
import { SubscribableOrPromise } from '../types';
/**
* Decides at subscription time which Observable will actually be subscribed.
*
* <span class="informal">`If` statement for Observables.</span>
*
* `iif` accepts a condition function and two Observables. When
* an Observable returned by the operator is subscribed, condition function will be called.
* Based on what boolean it returns at that moment, consumer will subscribe either to
* the first Observable (if condition was true) or to the second (if condition was false). Condition
* function may also not return anything - in that case condition will be evaluated as false and
* second Observable will be subscribed.
*
* Note that Observables for both cases (true and false) are optional. If condition points to an Observable that
* was left undefined, resulting stream will simply complete immediately. That allows you to, rather
* than controlling which Observable will be subscribed, decide at runtime if consumer should have access
* to given Observable or not.
*
* If you have more complex logic that requires decision between more than two Observables, {@link defer}
* will probably be a better choice. Actually `iif` can be easily implemented with {@link defer}
* and exists only for convenience and readability reasons.
*
*
* ## Examples
* ### Change at runtime which Observable will be subscribed
* ```ts
* import { iif, of } from 'rxjs';
*
* let subscribeToFirst;
* const firstOrSecond = iif(
* () => subscribeToFirst,
* of('first'),
* of('second'),
* );
*
* subscribeToFirst = true;
* firstOrSecond.subscribe(value => console.log(value));
*
* // Logs:
* // "first"
*
* subscribeToFirst = false;
* firstOrSecond.subscribe(value => console.log(value));
*
* // Logs:
* // "second"
*
* ```
*
* ### Control an access to an Observable
* ```ts
* let accessGranted;
* const observableIfYouHaveAccess = iif(
* () => accessGranted,
* of('It seems you have an access...'), // Note that only one Observable is passed to the operator.
* );
*
* accessGranted = true;
* observableIfYouHaveAccess.subscribe(
* value => console.log(value),
* err => {},
* () => console.log('The end'),
* );
*
* // Logs:
* // "It seems you have an access..."
* // "The end"
*
* accessGranted = false;
* observableIfYouHaveAccess.subscribe(
* value => console.log(value),
* err => {},
* () => console.log('The end'),
* );
*
* // Logs:
* // "The end"
* ```
*
* @see {@link defer}
*
* @param {function(): boolean} condition Condition which Observable should be chosen.
* @param {Observable} [trueObservable] An Observable that will be subscribed if condition is true.
* @param {Observable} [falseObservable] An Observable that will be subscribed if condition is false.
* @return {Observable} Either first or second Observable, depending on condition.
* @static true
* @name iif
* @owner Observable
*/
export function iif<T = never, F = never>(
condition: () => boolean,
trueResult: SubscribableOrPromise<T> = EMPTY,
falseResult: SubscribableOrPromise<F> = EMPTY
): Observable<T|F> {
return defer(() => condition() ? trueResult : falseResult);
}

83
node_modules/rxjs/src/internal/observable/interval.ts generated vendored Normal file
View File

@ -0,0 +1,83 @@
import { Observable } from '../Observable';
import { async } from '../scheduler/async';
import { SchedulerAction, SchedulerLike } from '../types';
import { isNumeric } from '../util/isNumeric';
import { Subscriber } from '../Subscriber';
/**
* Creates an Observable that emits sequential numbers every specified
* interval of time, on a specified {@link SchedulerLike}.
*
* <span class="informal">Emits incremental numbers periodically in time.
* </span>
*
* ![](interval.png)
*
* `interval` returns an Observable that emits an infinite sequence of
* ascending integers, with a constant interval of time of your choosing
* between those emissions. The first emission is not sent immediately, but
* only after the first period has passed. By default, this operator uses the
* `async` {@link SchedulerLike} to provide a notion of time, but you may pass any
* {@link SchedulerLike} to it.
*
* ## Example
* Emits ascending numbers, one every second (1000ms) up to the number 3
* ```ts
* import { interval } from 'rxjs';
* import { take } from 'rxjs/operators';
*
* const numbers = interval(1000);
*
* const takeFourNumbers = numbers.pipe(take(4));
*
* takeFourNumbers.subscribe(x => console.log('Next: ', x));
*
* // Logs:
* // Next: 0
* // Next: 1
* // Next: 2
* // Next: 3
* ```
*
* @see {@link timer}
* @see {@link delay}
*
* @param {number} [period=0] The interval size in milliseconds (by default)
* or the time unit determined by the scheduler's clock.
* @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for scheduling
* the emission of values, and providing a notion of "time".
* @return {Observable} An Observable that emits a sequential number each time
* interval.
* @static true
* @name interval
* @owner Observable
*/
export function interval(period = 0,
scheduler: SchedulerLike = async): Observable<number> {
if (!isNumeric(period) || period < 0) {
period = 0;
}
if (!scheduler || typeof scheduler.schedule !== 'function') {
scheduler = async;
}
return new Observable<number>(subscriber => {
subscriber.add(
scheduler.schedule(dispatch, period, { subscriber, counter: 0, period })
);
return subscriber;
});
}
function dispatch(this: SchedulerAction<IntervalState>, state: IntervalState) {
const { subscriber, counter, period } = state;
subscriber.next(counter);
this.schedule({ subscriber, counter: counter + 1, period }, period);
}
interface IntervalState {
subscriber: Subscriber<number>;
counter: number;
period: number;
}

140
node_modules/rxjs/src/internal/observable/merge.ts generated vendored Normal file
View File

@ -0,0 +1,140 @@
import { Observable } from '../Observable';
import { ObservableInput, SchedulerLike} from '../types';
import { isScheduler } from '../util/isScheduler';
import { mergeAll } from '../operators/mergeAll';
import { fromArray } from './fromArray';
/* tslint:disable:max-line-length */
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T>(v1: ObservableInput<T>, scheduler: SchedulerLike): Observable<T>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T>(v1: ObservableInput<T>, concurrent: number, scheduler: SchedulerLike): Observable<T>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>, scheduler: SchedulerLike): Observable<T | T2>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, scheduler: SchedulerLike): Observable<T | T2 | T3>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2 | T3>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, concurrent: number, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>;
export function merge<T>(v1: ObservableInput<T>): Observable<T>;
export function merge<T>(v1: ObservableInput<T>, concurrent?: number): Observable<T>;
export function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>): Observable<T | T2>;
export function merge<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>, concurrent?: number): Observable<T | T2>;
export function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<T | T2 | T3>;
export function merge<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, concurrent?: number): Observable<T | T2 | T3>;
export function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<T | T2 | T3 | T4>;
export function merge<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, concurrent?: number): Observable<T | T2 | T3 | T4>;
export function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<T | T2 | T3 | T4 | T5>;
export function merge<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, concurrent?: number): Observable<T | T2 | T3 | T4 | T5>;
export function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<T | T2 | T3 | T4 | T5 | T6>;
export function merge<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, concurrent?: number): Observable<T | T2 | T3 | T4 | T5 | T6>;
export function merge<T>(...observables: (ObservableInput<T> | number)[]): Observable<T>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T>(...observables: (ObservableInput<T> | SchedulerLike | number)[]): Observable<T>;
export function merge<T, R>(...observables: (ObservableInput<any> | number)[]): Observable<R>;
/** @deprecated use {@link scheduled} and {@link mergeAll} (e.g. `scheduled([ob1, ob2, ob3], scheduled).pipe(mergeAll())*/
export function merge<T, R>(...observables: (ObservableInput<any> | SchedulerLike | number)[]): Observable<R>;
/* tslint:enable:max-line-length */
/**
* Creates an output Observable which concurrently emits all values from every
* given input Observable.
*
* <span class="informal">Flattens multiple Observables together by blending
* their values into one Observable.</span>
*
* ![](merge.png)
*
* `merge` subscribes to each given input Observable (as arguments), and simply
* forwards (without doing any transformation) all the values from all the input
* Observables to the output Observable. The output Observable only completes
* once all input Observables have completed. Any error delivered by an input
* Observable will be immediately emitted on the output Observable.
*
* ## Examples
* ### Merge together two Observables: 1s interval and clicks
* ```ts
* import { merge, fromEvent, interval } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const timer = interval(1000);
* const clicksOrTimer = merge(clicks, timer);
* clicksOrTimer.subscribe(x => console.log(x));
*
* // Results in the following:
* // timer will emit ascending values, one every second(1000ms) to console
* // clicks logs MouseEvents to console everytime the "document" is clicked
* // Since the two streams are merged you see these happening
* // as they occur.
* ```
*
* ### Merge together 3 Observables, but only 2 run concurrently
* ```ts
* import { merge, interval } from 'rxjs';
* import { take } from 'rxjs/operators';
*
* const timer1 = interval(1000).pipe(take(10));
* const timer2 = interval(2000).pipe(take(6));
* const timer3 = interval(500).pipe(take(10));
* const concurrent = 2; // the argument
* const merged = merge(timer1, timer2, timer3, concurrent);
* merged.subscribe(x => console.log(x));
*
* // Results in the following:
* // - First timer1 and timer2 will run concurrently
* // - timer1 will emit a value every 1000ms for 10 iterations
* // - timer2 will emit a value every 2000ms for 6 iterations
* // - after timer1 hits it's max iteration, timer2 will
* // continue, and timer3 will start to run concurrently with timer2
* // - when timer2 hits it's max iteration it terminates, and
* // timer3 will continue to emit a value every 500ms until it is complete
* ```
*
* @see {@link mergeAll}
* @see {@link mergeMap}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
*
* @param {...ObservableInput} observables Input Observables to merge together.
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
* Observables being subscribed to concurrently.
* @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for managing
* concurrency of input Observables.
* @return {Observable} an Observable that emits items that are the result of
* every input Observable.
* @static true
* @name merge
* @owner Observable
*/
export function merge<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike | number>): Observable<R> {
let concurrent = Number.POSITIVE_INFINITY;
let scheduler: SchedulerLike = null;
let last: any = observables[observables.length - 1];
if (isScheduler(last)) {
scheduler = <SchedulerLike>observables.pop();
if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
concurrent = <number>observables.pop();
}
} else if (typeof last === 'number') {
concurrent = <number>observables.pop();
}
if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {
return <Observable<R>>observables[0];
}
return mergeAll<R>(concurrent)(fromArray<any>(observables, scheduler));
}

41
node_modules/rxjs/src/internal/observable/never.ts generated vendored Normal file
View File

@ -0,0 +1,41 @@
import { Observable } from '../Observable';
import { noop } from '../util/noop';
/**
* An Observable that emits no items to the Observer and never completes.
*
* ![](never.png)
*
* A simple Observable that emits neither values nor errors nor the completion
* notification. It can be used for testing purposes or for composing with other
* Observables. Please note that by never emitting a complete notification, this
* Observable keeps the subscription from being disposed automatically.
* Subscriptions need to be manually disposed.
*
* ## Example
* ### Emit the number 7, then never emit anything else (not even complete)
* ```ts
* import { NEVER } from 'rxjs';
* import { startWith } from 'rxjs/operators';
*
* function info() {
* console.log('Will not be called');
* }
* const result = NEVER.pipe(startWith(7));
* result.subscribe(x => console.log(x), info, info);
*
* ```
*
* @see {@link Observable}
* @see {@link index/EMPTY}
* @see {@link of}
* @see {@link throwError}
*/
export const NEVER = new Observable<never>(noop);
/**
* @deprecated Deprecated in favor of using {@link NEVER} constant.
*/
export function never () {
return NEVER;
}

110
node_modules/rxjs/src/internal/observable/of.ts generated vendored Normal file
View File

@ -0,0 +1,110 @@
import { SchedulerLike } from '../types';
import { isScheduler } from '../util/isScheduler';
import { fromArray } from './fromArray';
import { Observable } from '../Observable';
import { scheduleArray } from '../scheduled/scheduleArray';
/* tslint:disable:max-line-length */
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T>(a: T, scheduler: SchedulerLike): Observable<T>;
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T, T2>(a: T, b: T2, scheduler: SchedulerLike): Observable<T | T2>;
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T, T2, T3>(a: T, b: T2, c: T3, scheduler: SchedulerLike): Observable<T | T2 | T3>;
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4>;
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5>;
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, scheduler: SchedulerLike): Observable<T | T2 | T3 | T4 | T5 | T6>;
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, scheduler: SchedulerLike):
Observable<T | T2 | T3 | T4 | T5 | T6 | T7>;
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, scheduler: SchedulerLike):
Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>;
/** @deprecated use {@link scheduled} instead `scheduled([a, b, c], scheduler)` */
export function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9, scheduler: SchedulerLike):
Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;
export function of<T>(...args: (T | SchedulerLike)[]): Observable<T>;
// TODO(benlesh): Update the typings for this when we can switch to TS 3.x
export function of<T>(a: T): Observable<T>;
export function of<T, T2>(a: T, b: T2): Observable<T | T2>;
export function of<T, T2, T3>(a: T, b: T2, c: T3): Observable<T | T2 | T3>;
export function of<T, T2, T3, T4>(a: T, b: T2, c: T3, d: T4): Observable<T | T2 | T3 | T4>;
export function of<T, T2, T3, T4, T5>(a: T, b: T2, c: T3, d: T4, e: T5): Observable<T | T2 | T3 | T4 | T5>;
export function of<T, T2, T3, T4, T5, T6>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6): Observable<T | T2 | T3 | T4 | T5 | T6>;
export function of<T, T2, T3, T4, T5, T6, T7>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7):
Observable<T | T2 | T3 | T4 | T5 | T6 | T7>;
export function of<T, T2, T3, T4, T5, T6, T7, T8>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8):
Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8>;
export function of<T, T2, T3, T4, T5, T6, T7, T8, T9>(a: T, b: T2, c: T3, d: T4, e: T5, f: T6, g: T7, h: T8, i: T9):
Observable<T | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;
export function of<T>(...args: T[]): Observable<T>;
/* tslint:enable:max-line-length */
/**
* Converts the arguments to an observable sequence.
*
* <span class="informal">Each argument becomes a `next` notification.</span>
*
* ![](of.png)
*
* Unlike {@link from}, it does not do any flattening and emits each argument in whole
* as a separate `next` notification.
*
* ## Examples
*
* Emit the values `10, 20, 30`
*
* ```ts
* import { of } from 'rxjs';
*
* of(10, 20, 30)
* .subscribe(
* next => console.log('next:', next),
* err => console.log('error:', err),
* () => console.log('the end'),
* );
* // result:
* // 'next: 10'
* // 'next: 20'
* // 'next: 30'
*
* ```
*
* Emit the array `[1,2,3]`
*
* ```ts
* import { of } from 'rxjs';
*
* of([1,2,3])
* .subscribe(
* next => console.log('next:', next),
* err => console.log('error:', err),
* () => console.log('the end'),
* );
* // result:
* // 'next: [1,2,3]'
* ```
*
* @see {@link from}
* @see {@link range}
*
* @param {...T} values A comma separated list of arguments you want to be emitted
* @return {Observable} An Observable that emits the arguments
* described above and then completes.
* @method of
* @owner Observable
*/
export function of<T>(...args: Array<T | SchedulerLike>): Observable<T> {
let scheduler = args[args.length - 1] as SchedulerLike;
if (isScheduler(scheduler)) {
args.pop();
return scheduleArray(args as T[], scheduler);
} else {
return fromArray(args as T[]);
}
}

View File

@ -0,0 +1,102 @@
import { Observable } from '../Observable';
import { ObservableInput } from '../types';
import { from } from './from';
import { isArray } from '../util/isArray';
import { EMPTY } from './empty';
/* tslint:disable:max-line-length */
export function onErrorResumeNext<R>(v: ObservableInput<R>): Observable<R>;
export function onErrorResumeNext<T2, T3, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<R>;
export function onErrorResumeNext<T2, T3, T4, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<R>;
export function onErrorResumeNext<T2, T3, T4, T5, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<R>;
export function onErrorResumeNext<T2, T3, T4, T5, T6, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<R>;
export function onErrorResumeNext<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>;
export function onErrorResumeNext<R>(array: ObservableInput<any>[]): Observable<R>;
/* tslint:enable:max-line-length */
/**
* When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one
* that was passed.
*
* <span class="informal">Execute series of Observables no matter what, even if it means swallowing errors.</span>
*
* ![](onErrorResumeNext.png)
*
* `onErrorResumeNext` Will subscribe to each observable source it is provided, in order.
* If the source it's subscribed to emits an error or completes, it will move to the next source
* without error.
*
* If `onErrorResumeNext` is provided no arguments, or a single, empty array, it will return {@link index/EMPTY}.
*
* `onErrorResumeNext` is basically {@link concat}, only it will continue, even if one of its
* sources emits an error.
*
* Note that there is no way to handle any errors thrown by sources via the result of
* `onErrorResumeNext`. If you want to handle errors thrown in any given source, you can
* always use the {@link catchError} operator on them before passing them into `onErrorResumeNext`.
*
* ## Example
* Subscribe to the next Observable after map fails</caption>
* ```ts
* import { onErrorResumeNext, of } from 'rxjs';
* import { map } from 'rxjs/operators';
*
* onErrorResumeNext(
* of(1, 2, 3, 0).pipe(
* map(x => {
* if (x === 0) throw Error();
* return 10 / x;
* })
* ),
* of(1, 2, 3),
* )
* .subscribe(
* val => console.log(val),
* err => console.log(err), // Will never be called.
* () => console.log('done'),
* );
*
* // Logs:
* // 10
* // 5
* // 3.3333333333333335
* // 1
* // 2
* // 3
* // "done"
* ```
*
* @see {@link concat}
* @see {@link catchError}
*
* @param {...ObservableInput} sources Observables (or anything that *is* observable) passed either directly or as an array.
* @return {Observable} An Observable that concatenates all sources, one after the other,
* ignoring all errors, such that any error causes it to move on to the next source.
*/
export function onErrorResumeNext<T, R>(...sources: Array<ObservableInput<any> |
Array<ObservableInput<any>> |
((...values: Array<any>) => R)>): Observable<R> {
if (sources.length === 0) {
return EMPTY;
}
const [ first, ...remainder ] = sources;
if (sources.length === 1 && isArray(first)) {
return onErrorResumeNext(...first);
}
return new Observable(subscriber => {
const subNext = () => subscriber.add(
onErrorResumeNext(...remainder).subscribe(subscriber)
);
return from(first).subscribe({
next(value) { subscriber.next(value); },
error: subNext,
complete: subNext,
});
});
}

91
node_modules/rxjs/src/internal/observable/pairs.ts generated vendored Normal file
View File

@ -0,0 +1,91 @@
import { Observable } from '../Observable';
import { SchedulerAction, SchedulerLike } from '../types';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
/**
* Convert an object into an Observable of `[key, value]` pairs.
*
* <span class="informal">Turn entries of an object into a stream.</span>
*
* <img src="./img/pairs.png" width="100%">
*
* `pairs` takes an arbitrary object and returns an Observable that emits arrays. Each
* emitted array has exactly two elements - the first is a key from the object
* and the second is a value corresponding to that key. Keys are extracted from
* an object via `Object.keys` function, which means that they will be only
* enumerable keys that are present on an object directly - not ones inherited
* via prototype chain.
*
* By default these arrays are emitted synchronously. To change that you can
* pass a {@link SchedulerLike} as a second argument to `pairs`.
*
* @example <caption>Converts a javascript object to an Observable</caption>
* ```ts
* import { pairs } from 'rxjs';
*
* const obj = {
* foo: 42,
* bar: 56,
* baz: 78
* };
*
* pairs(obj)
* .subscribe(
* value => console.log(value),
* err => {},
* () => console.log('the end!')
* );
*
* // Logs:
* // ["foo", 42],
* // ["bar", 56],
* // ["baz", 78],
* // "the end!"
* ```
*
* @param {Object} obj The object to inspect and turn into an
* Observable sequence.
* @param {Scheduler} [scheduler] An optional IScheduler to schedule
* when resulting Observable will emit values.
* @returns {(Observable<Array<string|T>>)} An observable sequence of
* [key, value] pairs from the object.
*/
export function pairs<T>(obj: Object, scheduler?: SchedulerLike): Observable<[string, T]> {
if (!scheduler) {
return new Observable<[string, T]>(subscriber => {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length && !subscriber.closed; i++) {
const key = keys[i];
if (obj.hasOwnProperty(key)) {
subscriber.next([key, obj[key]]);
}
}
subscriber.complete();
});
} else {
return new Observable<[string, T]>(subscriber => {
const keys = Object.keys(obj);
const subscription = new Subscription();
subscription.add(
scheduler.schedule<{ keys: string[], index: number, subscriber: Subscriber<[string, T]>, subscription: Subscription, obj: Object }>
(dispatch, 0, { keys, index: 0, subscriber, subscription, obj }));
return subscription;
});
}
}
/** @internal */
export function dispatch<T>(this: SchedulerAction<any>,
state: { keys: string[], index: number, subscriber: Subscriber<[string, T]>, subscription: Subscription, obj: Object }) {
const { keys, index, subscriber, subscription, obj } = state;
if (!subscriber.closed) {
if (index < keys.length) {
const key = keys[index];
subscriber.next([key, obj[key]]);
subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
} else {
subscriber.complete();
}
}
}

67
node_modules/rxjs/src/internal/observable/partition.ts generated vendored Normal file
View File

@ -0,0 +1,67 @@
import { not } from '../util/not';
import { subscribeTo } from '../util/subscribeTo';
import { filter } from '../operators/filter';
import { ObservableInput } from '../types';
import { Observable } from '../Observable';
/**
* Splits the source Observable into two, one with values that satisfy a
* predicate, and another with values that don't satisfy the predicate.
*
* <span class="informal">It's like {@link filter}, but returns two Observables:
* one like the output of {@link filter}, and the other with values that did not
* pass the condition.</span>
*
* ![](partition.png)
*
* `partition` outputs an array with two Observables that partition the values
* from the source Observable through the given `predicate` function. The first
* Observable in that array emits source values for which the predicate argument
* returns true. The second Observable emits source values for which the
* predicate returns false. The first behaves like {@link filter} and the second
* behaves like {@link filter} with the predicate negated.
*
* ## Example
* Partition a set of numbers into odds and evens observables
* ```ts
* import { of, partition } from 'rxjs';
*
* const observableValues = of(1, 2, 3, 4, 5, 6);
* const [evens$, odds$] = partition(observableValues, (value, index) => value % 2 === 0);
*
* odds$.subscribe(x => console.log('odds', x));
* evens$.subscribe(x => console.log('evens', x));
*
* // Logs:
* // odds 1
* // odds 3
* // odds 5
* // evens 2
* // evens 4
* // evens 6
* ```
*
* @see {@link filter}
*
* @param {function(value: T, index: number): boolean} predicate A function that
* evaluates each value emitted by the source Observable. If it returns `true`,
* the value is emitted on the first Observable in the returned array, if
* `false` the value is emitted on the second Observable in the array. The
* `index` parameter is the number `i` for the i-th source emission that has
* happened since the subscription, starting from the number `0`.
* @param {any} [thisArg] An optional argument to determine the value of `this`
* in the `predicate` function.
* @return {[Observable<T>, Observable<T>]} An array with two Observables: one
* with values that passed the predicate, and another with values that did not
* pass the predicate.
*/
export function partition<T>(
source: ObservableInput<T>,
predicate: (value: T, index: number) => boolean,
thisArg?: any
): [Observable<T>, Observable<T>] {
return [
filter(predicate, thisArg)(new Observable<T>(subscribeTo(source))),
filter(not(predicate, thisArg) as any)(new Observable<T>(subscribeTo(source)))
] as [Observable<T>, Observable<T>];
}

140
node_modules/rxjs/src/internal/observable/race.ts generated vendored Normal file
View File

@ -0,0 +1,140 @@
import { Observable } from '../Observable';
import { isArray } from '../util/isArray';
import { fromArray } from './fromArray';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { TeardownLogic, ObservableInput } from '../types';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
// tslint:disable:max-line-length
export function race<A>(arg: [ObservableInput<A>]): Observable<A>;
export function race<A, B>(arg: [ObservableInput<A>, ObservableInput<B>]): Observable<A | B>;
export function race<A, B, C>(arg: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>]): Observable<A | B | C>;
export function race<A, B, C, D>(arg: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>]): Observable<A | B | C | D>;
export function race<A, B, C, D, E>(arg: [ObservableInput<A>, ObservableInput<B>, ObservableInput<C>, ObservableInput<D>, ObservableInput<E>]): Observable<A | B | C | D | E>;
export function race<T>(arg: ObservableInput<T>[]): Observable<T>;
export function race(arg: ObservableInput<any>[]): Observable<{}>;
export function race<A>(a: ObservableInput<A>): Observable<A>;
export function race<A, B>(a: ObservableInput<A>, b: ObservableInput<B>): Observable<A | B>;
export function race<A, B, C>(a: ObservableInput<A>, b: ObservableInput<B>, c: ObservableInput<C>): Observable<A | B | C>;
export function race<A, B, C, D>(a: ObservableInput<A>, b: ObservableInput<B>, c: ObservableInput<C>, d: ObservableInput<D>): Observable<A | B | C | D>;
export function race<A, B, C, D, E>(a: ObservableInput<A>, b: ObservableInput<B>, c: ObservableInput<C>, d: ObservableInput<D>, e: ObservableInput<E>): Observable<A | B | C | D | E>;
// tslint:enable:max-line-length
export function race<T>(observables: ObservableInput<T>[]): Observable<T>;
export function race(observables: ObservableInput<any>[]): Observable<{}>;
export function race<T>(...observables: ObservableInput<T>[]): Observable<T>;
export function race(...observables: ObservableInput<any>[]): Observable<{}>;
/**
* Returns an Observable that mirrors the first source Observable to emit an item.
*
* ## Example
* ### Subscribes to the observable that was the first to start emitting.
*
* ```ts
* import { race, interval } from 'rxjs';
* import { mapTo } from 'rxjs/operators';
*
* const obs1 = interval(1000).pipe(mapTo('fast one'));
* const obs2 = interval(3000).pipe(mapTo('medium one'));
* const obs3 = interval(5000).pipe(mapTo('slow one'));
*
* race(obs3, obs1, obs2)
* .subscribe(
* winner => console.log(winner)
* );
*
* // result:
* // a series of 'fast one'
* ```
*
* @param {...Observables} ...observables sources used to race for which Observable emits first.
* @return {Observable} an Observable that mirrors the output of the first Observable to emit an item.
* @static true
* @name race
* @owner Observable
*/
export function race<T>(...observables: ObservableInput<any>[]): Observable<T> {
// if the only argument is an array, it was most likely called with
// `race([obs1, obs2, ...])`
if (observables.length === 1) {
if (isArray(observables[0])) {
observables = observables[0] as Observable<any>[];
} else {
return observables[0] as Observable<T>;
}
}
return fromArray(observables, undefined).lift(new RaceOperator<T>());
}
export class RaceOperator<T> implements Operator<T, T> {
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new RaceSubscriber(subscriber));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class RaceSubscriber<T> extends OuterSubscriber<T, T> {
private hasFirst: boolean = false;
private observables: Observable<any>[] = [];
private subscriptions: Subscription[] = [];
constructor(destination: Subscriber<T>) {
super(destination);
}
protected _next(observable: any): void {
this.observables.push(observable);
}
protected _complete() {
const observables = this.observables;
const len = observables.length;
if (len === 0) {
this.destination.complete();
} else {
for (let i = 0; i < len && !this.hasFirst; i++) {
let observable = observables[i];
let subscription = subscribeToResult(this, observable, observable as any, i);
if (this.subscriptions) {
this.subscriptions.push(subscription);
}
this.add(subscription);
}
this.observables = null;
}
}
notifyNext(outerValue: T, innerValue: T,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, T>): void {
if (!this.hasFirst) {
this.hasFirst = true;
for (let i = 0; i < this.subscriptions.length; i++) {
if (i !== outerIndex) {
let subscription = this.subscriptions[i];
subscription.unsubscribe();
this.remove(subscription);
}
}
this.subscriptions = null;
}
this.destination.next(innerValue);
}
}

90
node_modules/rxjs/src/internal/observable/range.ts generated vendored Normal file
View File

@ -0,0 +1,90 @@
import { SchedulerAction, SchedulerLike } from '../types';
import { Observable } from '../Observable';
/**
* Creates an Observable that emits a sequence of numbers within a specified
* range.
*
* <span class="informal">Emits a sequence of numbers in a range.</span>
*
* ![](range.png)
*
* `range` operator emits a range of sequential integers, in order, where you
* select the `start` of the range and its `length`. By default, uses no
* {@link SchedulerLike} and just delivers the notifications synchronously, but may use
* an optional {@link SchedulerLike} to regulate those deliveries.
*
* ## Example
* Emits the numbers 1 to 10</caption>
* ```ts
* import { range } from 'rxjs';
*
* const numbers = range(1, 10);
* numbers.subscribe(x => console.log(x));
* ```
* @see {@link timer}
* @see {@link index/interval}
*
* @param {number} [start=0] The value of the first integer in the sequence.
* @param {number} count The number of sequential integers to generate.
* @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling
* the emissions of the notifications.
* @return {Observable} An Observable of numbers that emits a finite range of
* sequential integers.
* @static true
* @name range
* @owner Observable
*/
export function range(start: number = 0,
count?: number,
scheduler?: SchedulerLike): Observable<number> {
return new Observable<number>(subscriber => {
if (count === undefined) {
count = start;
start = 0;
}
let index = 0;
let current = start;
if (scheduler) {
return scheduler.schedule(dispatch, 0, {
index, count, start, subscriber
});
} else {
do {
if (index++ >= count) {
subscriber.complete();
break;
}
subscriber.next(current++);
if (subscriber.closed) {
break;
}
} while (true);
}
return undefined;
});
}
/** @internal */
export function dispatch(this: SchedulerAction<any>, state: any) {
const { start, index, count, subscriber } = state;
if (index >= count) {
subscriber.complete();
return;
}
subscriber.next(start);
if (subscriber.closed) {
return;
}
state.index = index + 1;
state.start = start + 1;
this.schedule(state);
}

View File

@ -0,0 +1,84 @@
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
import { Subscriber } from '../Subscriber';
/**
* Creates an Observable that emits no items to the Observer and immediately
* emits an error notification.
*
* <span class="informal">Just emits 'error', and nothing else.
* </span>
*
* ![](throw.png)
*
* This static operator is useful for creating a simple Observable that only
* emits the error notification. It can be used for composing with other
* Observables, such as in a {@link mergeMap}.
*
* ## Examples
* ### Emit the number 7, then emit an error
* ```ts
* import { throwError, concat, of } from 'rxjs';
*
* const result = concat(of(7), throwError(new Error('oops!')));
* result.subscribe(x => console.log(x), e => console.error(e));
*
* // Logs:
* // 7
* // Error: oops!
* ```
*
* ---
*
* ### Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 2
* ```ts
* import { throwError, interval, of } from 'rxjs';
* import { mergeMap } from 'rxjs/operators';
*
* interval(1000).pipe(
* mergeMap(x => x === 2
* ? throwError('Twos are bad')
* : of('a', 'b', 'c')
* ),
* ).subscribe(x => console.log(x), e => console.error(e));
*
* // Logs:
* // a
* // b
* // c
* // a
* // b
* // c
* // Twos are bad
* ```
*
* @see {@link Observable}
* @see {@link empty}
* @see {@link never}
* @see {@link of}
*
* @param {any} error The particular Error to pass to the error notification.
* @param {SchedulerLike} [scheduler] A {@link SchedulerLike} to use for scheduling
* the emission of the error notification.
* @return {Observable} An error Observable: emits only the error notification
* using the given error argument.
* @static true
* @name throwError
* @owner Observable
*/
export function throwError(error: any, scheduler?: SchedulerLike): Observable<never> {
if (!scheduler) {
return new Observable(subscriber => subscriber.error(error));
} else {
return new Observable(subscriber => scheduler.schedule(dispatch, 0, { error, subscriber }));
}
}
interface DispatchArg {
error: any;
subscriber: Subscriber<any>;
}
function dispatch({ error, subscriber }: DispatchArg) {
subscriber.error(error);
}

101
node_modules/rxjs/src/internal/observable/timer.ts generated vendored Normal file
View File

@ -0,0 +1,101 @@
import { Observable } from '../Observable';
import { SchedulerAction, SchedulerLike } from '../types';
import { async } from '../scheduler/async';
import { isNumeric } from '../util/isNumeric';
import { isScheduler } from '../util/isScheduler';
import { Subscriber } from '../Subscriber';
/**
* Creates an Observable that starts emitting after an `dueTime` and
* emits ever increasing numbers after each `period` of time thereafter.
*
* <span class="informal">Its like {@link index/interval}, but you can specify when
* should the emissions start.</span>
*
* ![](timer.png)
*
* `timer` returns an Observable that emits an infinite sequence of ascending
* integers, with a constant interval of time, `period` of your choosing
* between those emissions. The first emission happens after the specified
* `dueTime`. The initial delay may be a `Date`. By default, this
* operator uses the {@link asyncScheduler} {@link SchedulerLike} to provide a notion of time, but you
* may pass any {@link SchedulerLike} to it. If `period` is not specified, the output
* Observable emits only one value, `0`. Otherwise, it emits an infinite
* sequence.
*
* ## Examples
* ### Emits ascending numbers, one every second (1000ms), starting after 3 seconds
* ```ts
* import { timer } from 'rxjs';
*
* const numbers = timer(3000, 1000);
* numbers.subscribe(x => console.log(x));
* ```
*
* ### Emits one number after five seconds
* ```ts
* import { timer } from 'rxjs';
*
* const numbers = timer(5000);
* numbers.subscribe(x => console.log(x));
* ```
* @see {@link index/interval}
* @see {@link delay}
*
* @param {number|Date} [dueTime] The initial delay time specified as a Date object or as an integer denoting
* milliseconds to wait before emitting the first value of 0`.
* @param {number|SchedulerLike} [periodOrScheduler] The period of time between emissions of the
* subsequent numbers.
* @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for scheduling
* the emission of values, and providing a notion of "time".
* @return {Observable} An Observable that emits a `0` after the
* `dueTime` and ever increasing numbers after each `period` of time
* thereafter.
* @static true
* @name timer
* @owner Observable
*/
export function timer(dueTime: number | Date = 0,
periodOrScheduler?: number | SchedulerLike,
scheduler?: SchedulerLike): Observable<number> {
let period = -1;
if (isNumeric(periodOrScheduler)) {
period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler as any;
}
if (!isScheduler(scheduler)) {
scheduler = async;
}
return new Observable(subscriber => {
const due = isNumeric(dueTime)
? (dueTime as number)
: (+dueTime - scheduler.now());
return scheduler.schedule(dispatch, due, {
index: 0, period, subscriber
});
});
}
interface TimerState {
index: number;
period: number;
subscriber: Subscriber<number>;
}
function dispatch(this: SchedulerAction<TimerState>, state: TimerState) {
const { index, period, subscriber } = state;
subscriber.next(index);
if (subscriber.closed) {
return;
} else if (period === -1) {
return subscriber.complete();
}
state.index = index + 1;
this.schedule(state, period);
}

63
node_modules/rxjs/src/internal/observable/using.ts generated vendored Normal file
View File

@ -0,0 +1,63 @@
import { Observable } from '../Observable';
import { Unsubscribable, ObservableInput } from '../types';
import { from } from './from'; // from from from! LAWL
import { EMPTY } from './empty';
/**
* Creates an Observable that uses a resource which will be disposed at the same time as the Observable.
*
* <span class="informal">Use it when you catch yourself cleaning up after an Observable.</span>
*
* `using` is a factory operator, which accepts two functions. First function returns a disposable resource.
* It can be an arbitrary object that implements `unsubscribe` method. Second function will be injected with
* that object and should return an Observable. That Observable can use resource object during its execution.
* Both functions passed to `using` will be called every time someone subscribes - neither an Observable nor
* resource object will be shared in any way between subscriptions.
*
* When Observable returned by `using` is subscribed, Observable returned from the second function will be subscribed
* as well. All its notifications (nexted values, completion and error events) will be emitted unchanged by the output
* Observable. If however someone unsubscribes from the Observable or source Observable completes or errors by itself,
* the `unsubscribe` method on resource object will be called. This can be used to do any necessary clean up, which
* otherwise would have to be handled by hand. Note that complete or error notifications are not emitted when someone
* cancels subscription to an Observable via `unsubscribe`, so `using` can be used as a hook, allowing you to make
* sure that all resources which need to exist during an Observable execution will be disposed at appropriate time.
*
* @see {@link defer}
*
* @param {function(): ISubscription} resourceFactory A function which creates any resource object
* that implements `unsubscribe` method.
* @param {function(resource: ISubscription): Observable<T>} observableFactory A function which
* creates an Observable, that can use injected resource object.
* @return {Observable<T>} An Observable that behaves the same as Observable returned by `observableFactory`, but
* which - when completed, errored or unsubscribed - will also call `unsubscribe` on created resource object.
*/
export function using<T>(resourceFactory: () => Unsubscribable | void,
observableFactory: (resource: Unsubscribable | void) => ObservableInput<T> | void): Observable<T> {
return new Observable<T>(subscriber => {
let resource: Unsubscribable | void;
try {
resource = resourceFactory();
} catch (err) {
subscriber.error(err);
return undefined;
}
let result: ObservableInput<T> | void;
try {
result = observableFactory(resource);
} catch (err) {
subscriber.error(err);
return undefined;
}
const source = result ? from(result) : EMPTY;
const subscription = source.subscribe(subscriber);
return () => {
subscription.unsubscribe();
if (resource) {
resource.unsubscribe();
}
};
});
}

330
node_modules/rxjs/src/internal/observable/zip.ts generated vendored Normal file
View File

@ -0,0 +1,330 @@
import { Observable } from '../Observable';
import { fromArray } from './fromArray';
import { isArray } from '../util/isArray';
import { Operator } from '../Operator';
import { ObservableInput, PartialObserver, ObservedValueOf } from '../types';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { iterator as Symbol_iterator } from '../../internal/symbol/iterator';
/* tslint:disable:max-line-length */
/** @deprecated resultSelector is no longer supported, pipe to map instead */
export function zip<O1 extends ObservableInput<any>, R>(v1: O1, resultSelector: (v1: ObservedValueOf<O1>) => R): Observable<R>;
/** @deprecated resultSelector is no longer supported, pipe to map instead */
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, R>(v1: O1, v2: O2, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>) => R): Observable<R>;
/** @deprecated resultSelector is no longer supported, pipe to map instead */
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>) => R): Observable<R>;
/** @deprecated resultSelector is no longer supported, pipe to map instead */
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>) => R): Observable<R>;
/** @deprecated resultSelector is no longer supported, pipe to map instead */
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>) => R): Observable<R>;
/** @deprecated resultSelector is no longer supported, pipe to map instead */
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>, R>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6, resultSelector: (v1: ObservedValueOf<O1>, v2: ObservedValueOf<O2>, v3: ObservedValueOf<O3>, v4: ObservedValueOf<O4>, v5: ObservedValueOf<O5>, v6: ObservedValueOf<O6>) => R): Observable<R>;
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>>(v1: O1, v2: O2): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>]>;
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>]>;
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>]>;
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>]>;
export function zip<O1 extends ObservableInput<any>, O2 extends ObservableInput<any>, O3 extends ObservableInput<any>, O4 extends ObservableInput<any>, O5 extends ObservableInput<any>, O6 extends ObservableInput<any>>(v1: O1, v2: O2, v3: O3, v4: O4, v5: O5, v6: O6): Observable<[ObservedValueOf<O1>, ObservedValueOf<O2>, ObservedValueOf<O3>, ObservedValueOf<O4>, ObservedValueOf<O5>, ObservedValueOf<O6>]>;
export function zip<O extends ObservableInput<any>>(array: O[]): Observable<ObservedValueOf<O>[]>;
export function zip<R>(array: ObservableInput<any>[]): Observable<R>;
/** @deprecated resultSelector is no longer supported, pipe to map instead */
export function zip<O extends ObservableInput<any>, R>(array: O[], resultSelector: (...values: ObservedValueOf<O>[]) => R): Observable<R>;
/** @deprecated resultSelector is no longer supported, pipe to map instead */
export function zip<R>(array: ObservableInput<any>[], resultSelector: (...values: any[]) => R): Observable<R>;
export function zip<O extends ObservableInput<any>>(...observables: O[]): Observable<ObservedValueOf<O>[]>;
export function zip<O extends ObservableInput<any>, R>(...observables: Array<O | ((...values: ObservedValueOf<O>[]) => R)>): Observable<R>;
export function zip<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>;
/* tslint:enable:max-line-length */
/**
* Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
* of its input Observables.
*
* If the last parameter is a function, this function is used to compute the created value from the input values.
* Otherwise, an array of the input values is returned.
*
* ## Example
* Combine age and name from different sources
* ```ts
* import { zip, of } from 'rxjs';
* import { map } from 'rxjs/operators';
*
* let age$ = of<number>(27, 25, 29);
* let name$ = of<string>('Foo', 'Bar', 'Beer');
* let isDev$ = of<boolean>(true, true, false);
*
* zip(age$, name$, isDev$).pipe(
* map(([age, name, isDev]) => ({ age, name, isDev })),
* )
* .subscribe(x => console.log(x));
*
* // outputs
* // { age: 27, name: 'Foo', isDev: true }
* // { age: 25, name: 'Bar', isDev: true }
* // { age: 29, name: 'Beer', isDev: false }
* ```
* @param observables
* @return {Observable<R>}
* @static true
* @name zip
* @owner Observable
*/
export function zip<O extends ObservableInput<any>, R>(
...observables: Array<O | ((...values: ObservedValueOf<O>[]) => R)>
): Observable<ObservedValueOf<O>[]|R> {
const resultSelector = <((...ys: Array<any>) => R)> observables[observables.length - 1];
if (typeof resultSelector === 'function') {
observables.pop();
}
return fromArray(observables, undefined).lift(new ZipOperator(resultSelector));
}
export class ZipOperator<T, R> implements Operator<T, R> {
resultSelector: (...values: Array<any>) => R;
constructor(resultSelector?: (...values: Array<any>) => R) {
this.resultSelector = resultSelector;
}
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class ZipSubscriber<T, R> extends Subscriber<T> {
private values: any;
private resultSelector: (...values: Array<any>) => R;
private iterators: LookAheadIterator<any>[] = [];
private active = 0;
constructor(destination: Subscriber<R>,
resultSelector?: (...values: Array<any>) => R,
values: any = Object.create(null)) {
super(destination);
this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null;
this.values = values;
}
protected _next(value: any) {
const iterators = this.iterators;
if (isArray(value)) {
iterators.push(new StaticArrayIterator(value));
} else if (typeof value[Symbol_iterator] === 'function') {
iterators.push(new StaticIterator(value[Symbol_iterator]()));
} else {
iterators.push(new ZipBufferIterator(this.destination, this, value));
}
}
protected _complete() {
const iterators = this.iterators;
const len = iterators.length;
this.unsubscribe();
if (len === 0) {
this.destination.complete();
return;
}
this.active = len;
for (let i = 0; i < len; i++) {
let iterator: ZipBufferIterator<any, any> = <any>iterators[i];
if (iterator.stillUnsubscribed) {
const destination = this.destination as Subscription;
destination.add(iterator.subscribe(iterator, i));
} else {
this.active--; // not an observable
}
}
}
notifyInactive() {
this.active--;
if (this.active === 0) {
this.destination.complete();
}
}
checkIterators() {
const iterators = this.iterators;
const len = iterators.length;
const destination = this.destination;
// abort if not all of them have values
for (let i = 0; i < len; i++) {
let iterator = iterators[i];
if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
return;
}
}
let shouldComplete = false;
const args: any[] = [];
for (let i = 0; i < len; i++) {
let iterator = iterators[i];
let result = iterator.next();
// check to see if it's completed now that you've gotten
// the next value.
if (iterator.hasCompleted()) {
shouldComplete = true;
}
if (result.done) {
destination.complete();
return;
}
args.push(result.value);
}
if (this.resultSelector) {
this._tryresultSelector(args);
} else {
destination.next(args);
}
if (shouldComplete) {
destination.complete();
}
}
protected _tryresultSelector(args: any[]) {
let result: any;
try {
result = this.resultSelector.apply(this, args);
} catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
}
}
interface LookAheadIterator<T> extends Iterator<T> {
hasValue(): boolean;
hasCompleted(): boolean;
}
class StaticIterator<T> implements LookAheadIterator<T> {
private nextResult: IteratorResult<T>;
constructor(private iterator: Iterator<T>) {
this.nextResult = iterator.next();
}
hasValue() {
return true;
}
next(): IteratorResult<T> {
const result = this.nextResult;
this.nextResult = this.iterator.next();
return result;
}
hasCompleted() {
const nextResult = this.nextResult;
return nextResult && nextResult.done;
}
}
class StaticArrayIterator<T> implements LookAheadIterator<T> {
private index = 0;
private length = 0;
constructor(private array: T[]) {
this.length = array.length;
}
[Symbol_iterator]() {
return this;
}
next(value?: any): IteratorResult<T> {
const i = this.index++;
const array = this.array;
return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
}
hasValue() {
return this.array.length > this.index;
}
hasCompleted() {
return this.array.length === this.index;
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class ZipBufferIterator<T, R> extends OuterSubscriber<T, R> implements LookAheadIterator<T> {
stillUnsubscribed = true;
buffer: T[] = [];
isComplete = false;
constructor(destination: PartialObserver<T>,
private parent: ZipSubscriber<T, R>,
private observable: Observable<T>) {
super(destination);
}
[Symbol_iterator]() {
return this;
}
// NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
// this is legit because `next()` will never be called by a subscription in this case.
next(): IteratorResult<T> {
const buffer = this.buffer;
if (buffer.length === 0 && this.isComplete) {
return { value: null, done: true };
} else {
return { value: buffer.shift(), done: false };
}
}
hasValue() {
return this.buffer.length > 0;
}
hasCompleted() {
return this.buffer.length === 0 && this.isComplete;
}
notifyComplete() {
if (this.buffer.length > 0) {
this.isComplete = true;
this.parent.notifyInactive();
} else {
this.destination.complete();
}
}
notifyNext(outerValue: T, innerValue: any,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
this.buffer.push(innerValue);
this.parent.checkIterators();
}
subscribe(value: any, index: number) {
return subscribeToResult<any, any>(this, this.observable, this, index);
}
}

128
node_modules/rxjs/src/internal/operators/audit.ts generated vendored Normal file
View File

@ -0,0 +1,128 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { Subscription } from '../Subscription';
import { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';
import { OuterSubscriber } from '../OuterSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
/**
* Ignores source values for a duration determined by another Observable, then
* emits the most recent value from the source Observable, then repeats this
* process.
*
* <span class="informal">It's like {@link auditTime}, but the silencing
* duration is determined by a second Observable.</span>
*
* ![](audit.png)
*
* `audit` is similar to `throttle`, but emits the last value from the silenced
* time window, instead of the first value. `audit` emits the most recent value
* from the source Observable on the output Observable as soon as its internal
* timer becomes disabled, and ignores source values while the timer is enabled.
* Initially, the timer is disabled. As soon as the first source value arrives,
* the timer is enabled by calling the `durationSelector` function with the
* source value, which returns the "duration" Observable. When the duration
* Observable emits a value or completes, the timer is disabled, then the most
* recent source value is emitted on the output Observable, and this process
* repeats for the next source value.
*
* ## Example
*
* Emit clicks at a rate of at most one click per second
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { audit } from 'rxjs/operators'
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(audit(ev => interval(1000)));
* result.subscribe(x => console.log(x));
* ```
* @see {@link auditTime}
* @see {@link debounce}
* @see {@link delayWhen}
* @see {@link sample}
* @see {@link throttle}
*
* @param {function(value: T): SubscribableOrPromise} durationSelector A function
* that receives a value from the source Observable, for computing the silencing
* duration, returned as an Observable or a Promise.
* @return {Observable<T>} An Observable that performs rate-limiting of
* emissions from the source Observable.
* @method audit
* @owner Observable
*/
export function audit<T>(durationSelector: (value: T) => SubscribableOrPromise<any>): MonoTypeOperatorFunction<T> {
return function auditOperatorFunction(source: Observable<T>) {
return source.lift(new AuditOperator(durationSelector));
};
}
class AuditOperator<T> implements Operator<T, T> {
constructor(private durationSelector: (value: T) => SubscribableOrPromise<any>) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new AuditSubscriber<T, T>(subscriber, this.durationSelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class AuditSubscriber<T, R> extends OuterSubscriber<T, R> {
private value: T;
private hasValue: boolean = false;
private throttled: Subscription;
constructor(destination: Subscriber<T>,
private durationSelector: (value: T) => SubscribableOrPromise<any>) {
super(destination);
}
protected _next(value: T): void {
this.value = value;
this.hasValue = true;
if (!this.throttled) {
let duration;
try {
const { durationSelector } = this;
duration = durationSelector(value);
} catch (err) {
return this.destination.error(err);
}
const innerSubscription = subscribeToResult(this, duration);
if (!innerSubscription || innerSubscription.closed) {
this.clearThrottle();
} else {
this.add(this.throttled = innerSubscription);
}
}
}
clearThrottle() {
const { value, hasValue, throttled } = this;
if (throttled) {
this.remove(throttled);
this.throttled = null;
throttled.unsubscribe();
}
if (hasValue) {
this.value = null;
this.hasValue = false;
this.destination.next(value);
}
}
notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void {
this.clearThrottle();
}
notifyComplete(): void {
this.clearThrottle();
}
}

57
node_modules/rxjs/src/internal/operators/auditTime.ts generated vendored Normal file
View File

@ -0,0 +1,57 @@
import { async } from '../scheduler/async';
import { audit } from './audit';
import { timer } from '../observable/timer';
import { MonoTypeOperatorFunction, SchedulerLike } from '../types';
/**
* Ignores source values for `duration` milliseconds, then emits the most recent
* value from the source Observable, then repeats this process.
*
* <span class="informal">When it sees a source value, it ignores that plus
* the next ones for `duration` milliseconds, and then it emits the most recent
* value from the source.</span>
*
* ![](auditTime.png)
*
* `auditTime` is similar to `throttleTime`, but emits the last value from the
* silenced time window, instead of the first value. `auditTime` emits the most
* recent value from the source Observable on the output Observable as soon as
* its internal timer becomes disabled, and ignores source values while the
* timer is enabled. Initially, the timer is disabled. As soon as the first
* source value arrives, the timer is enabled. After `duration` milliseconds (or
* the time unit determined internally by the optional `scheduler`) has passed,
* the timer is disabled, then the most recent source value is emitted on the
* output Observable, and this process repeats for the next source value.
* Optionally takes a {@link SchedulerLike} for managing timers.
*
* ## Example
*
* Emit clicks at a rate of at most one click per second
* ```ts
* import { fromEvent } from 'rxjs';
* import { auditTime } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(auditTime(1000));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link audit}
* @see {@link debounceTime}
* @see {@link delay}
* @see {@link sampleTime}
* @see {@link throttleTime}
*
* @param {number} duration Time to wait before emitting the most recent source
* value, measured in milliseconds or the time unit determined internally
* by the optional `scheduler`.
* @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for
* managing the timers that handle the rate-limiting behavior.
* @return {Observable<T>} An Observable that performs rate-limiting of
* emissions from the source Observable.
* @method auditTime
* @owner Observable
*/
export function auditTime<T>(duration: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {
return audit(() => timer(duration, scheduler));
}

89
node_modules/rxjs/src/internal/operators/buffer.ts generated vendored Normal file
View File

@ -0,0 +1,89 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { OperatorFunction } from '../types';
/**
* Buffers the source Observable values until `closingNotifier` emits.
*
* <span class="informal">Collects values from the past as an array, and emits
* that array only when another Observable emits.</span>
*
* ![](buffer.png)
*
* Buffers the incoming Observable values until the given `closingNotifier`
* Observable emits a value, at which point it emits the buffer on the output
* Observable and starts a new buffer internally, awaiting the next time
* `closingNotifier` emits.
*
* ## Example
*
* On every click, emit array of most recent interval events
*
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { buffer } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const intervalEvents = interval(1000);
* const buffered = intervalEvents.pipe(buffer(clicks));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link window}
*
* @param {Observable<any>} closingNotifier An Observable that signals the
* buffer to be emitted on the output Observable.
* @return {Observable<T[]>} An Observable of buffers, which are arrays of
* values.
* @method buffer
* @owner Observable
*/
export function buffer<T>(closingNotifier: Observable<any>): OperatorFunction<T, T[]> {
return function bufferOperatorFunction(source: Observable<T>) {
return source.lift(new BufferOperator<T>(closingNotifier));
};
}
class BufferOperator<T> implements Operator<T, T[]> {
constructor(private closingNotifier: Observable<any>) {
}
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferSubscriber<T> extends OuterSubscriber<T, any> {
private buffer: T[] = [];
constructor(destination: Subscriber<T[]>, closingNotifier: Observable<any>) {
super(destination);
this.add(subscribeToResult(this, closingNotifier));
}
protected _next(value: T) {
this.buffer.push(value);
}
notifyNext(outerValue: T, innerValue: any,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, any>): void {
const buffer = this.buffer;
this.buffer = [];
this.destination.next(buffer);
}
}

158
node_modules/rxjs/src/internal/operators/bufferCount.ts generated vendored Normal file
View File

@ -0,0 +1,158 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OperatorFunction, TeardownLogic } from '../types';
/**
* Buffers the source Observable values until the size hits the maximum
* `bufferSize` given.
*
* <span class="informal">Collects values from the past as an array, and emits
* that array only when its size reaches `bufferSize`.</span>
*
* ![](bufferCount.png)
*
* Buffers a number of values from the source Observable by `bufferSize` then
* emits the buffer and clears it, and starts a new buffer each
* `startBufferEvery` values. If `startBufferEvery` is not provided or is
* `null`, then new buffers are started immediately at the start of the source
* and when each buffer closes and is emitted.
*
* ## Examples
*
* Emit the last two click events as an array
*
* ```ts
* import { fromEvent } from 'rxjs';
* import { bufferCount } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferCount(2));
* buffered.subscribe(x => console.log(x));
* ```
*
* On every click, emit the last two click events as an array
*
* ```ts
* import { fromEvent } from 'rxjs';
* import { bufferCount } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferCount(2, 1));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link buffer}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link pairwise}
* @see {@link windowCount}
*
* @param {number} bufferSize The maximum size of the buffer emitted.
* @param {number} [startBufferEvery] Interval at which to start a new buffer.
* For example if `startBufferEvery` is `2`, then a new buffer will be started
* on every other value from the source. A new buffer is started at the
* beginning of the source by default.
* @return {Observable<T[]>} An Observable of arrays of buffered values.
* @method bufferCount
* @owner Observable
*/
export function bufferCount<T>(bufferSize: number, startBufferEvery: number = null): OperatorFunction<T, T[]> {
return function bufferCountOperatorFunction(source: Observable<T>) {
return source.lift(new BufferCountOperator<T>(bufferSize, startBufferEvery));
};
}
class BufferCountOperator<T> implements Operator<T, T[]> {
private subscriberClass: any;
constructor(private bufferSize: number, private startBufferEvery: number) {
if (!startBufferEvery || bufferSize === startBufferEvery) {
this.subscriberClass = BufferCountSubscriber;
} else {
this.subscriberClass = BufferSkipCountSubscriber;
}
}
call(subscriber: Subscriber<T[]>, source: any): TeardownLogic {
return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferCountSubscriber<T> extends Subscriber<T> {
private buffer: T[] = [];
constructor(destination: Subscriber<T[]>, private bufferSize: number) {
super(destination);
}
protected _next(value: T): void {
const buffer = this.buffer;
buffer.push(value);
if (buffer.length == this.bufferSize) {
this.destination.next(buffer);
this.buffer = [];
}
}
protected _complete(): void {
const buffer = this.buffer;
if (buffer.length > 0) {
this.destination.next(buffer);
}
super._complete();
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferSkipCountSubscriber<T> extends Subscriber<T> {
private buffers: Array<T[]> = [];
private count: number = 0;
constructor(destination: Subscriber<T[]>, private bufferSize: number, private startBufferEvery: number) {
super(destination);
}
protected _next(value: T): void {
const { bufferSize, startBufferEvery, buffers, count } = this;
this.count++;
if (count % startBufferEvery === 0) {
buffers.push([]);
}
for (let i = buffers.length; i--; ) {
const buffer = buffers[i];
buffer.push(value);
if (buffer.length === bufferSize) {
buffers.splice(i, 1);
this.destination.next(buffer);
}
}
}
protected _complete(): void {
const { buffers, destination } = this;
while (buffers.length > 0) {
let buffer = buffers.shift();
if (buffer.length > 0) {
destination.next(buffer);
}
}
super._complete();
}
}

250
node_modules/rxjs/src/internal/operators/bufferTime.ts generated vendored Normal file
View File

@ -0,0 +1,250 @@
import { Operator } from '../Operator';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { isScheduler } from '../util/isScheduler';
import { OperatorFunction, SchedulerAction, SchedulerLike } from '../types';
/* tslint:disable:max-line-length */
export function bufferTime<T>(bufferTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;
export function bufferTime<T>(bufferTimeSpan: number, bufferCreationInterval: number | null | undefined, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;
export function bufferTime<T>(bufferTimeSpan: number, bufferCreationInterval: number | null | undefined, maxBufferSize: number, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;
/* tslint:enable:max-line-length */
/**
* Buffers the source Observable values for a specific time period.
*
* <span class="informal">Collects values from the past as an array, and emits
* those arrays periodically in time.</span>
*
* ![](bufferTime.png)
*
* Buffers values from the source for a specific time duration `bufferTimeSpan`.
* Unless the optional argument `bufferCreationInterval` is given, it emits and
* resets the buffer every `bufferTimeSpan` milliseconds. If
* `bufferCreationInterval` is given, this operator opens the buffer every
* `bufferCreationInterval` milliseconds and closes (emits and resets) the
* buffer every `bufferTimeSpan` milliseconds. When the optional argument
* `maxBufferSize` is specified, the buffer will be closed either after
* `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.
*
* ## Examples
*
* Every second, emit an array of the recent click events
*
* ```ts
* import { fromEvent } from 'rxjs';
* import { bufferTime } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferTime(1000));
* buffered.subscribe(x => console.log(x));
* ```
*
* Every 5 seconds, emit the click events from the next 2 seconds
*
* ```ts
* import { fromEvent } from 'rxjs';
* import { bufferTime } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferTime(2000, 5000));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link buffer}
* @see {@link bufferCount}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link windowTime}
*
* @param {number} bufferTimeSpan The amount of time to fill each buffer array.
* @param {number} [bufferCreationInterval] The interval at which to start new
* buffers.
* @param {number} [maxBufferSize] The maximum buffer size.
* @param {SchedulerLike} [scheduler=async] The scheduler on which to schedule the
* intervals that determine buffer boundaries.
* @return {Observable<T[]>} An observable of arrays of buffered values.
* @method bufferTime
* @owner Observable
*/
export function bufferTime<T>(bufferTimeSpan: number): OperatorFunction<T, T[]> {
let length: number = arguments.length;
let scheduler: SchedulerLike = async;
if (isScheduler(arguments[arguments.length - 1])) {
scheduler = arguments[arguments.length - 1];
length--;
}
let bufferCreationInterval: number = null;
if (length >= 2) {
bufferCreationInterval = arguments[1];
}
let maxBufferSize: number = Number.POSITIVE_INFINITY;
if (length >= 3) {
maxBufferSize = arguments[2];
}
return function bufferTimeOperatorFunction(source: Observable<T>) {
return source.lift(new BufferTimeOperator<T>(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
};
}
class BufferTimeOperator<T> implements Operator<T, T[]> {
constructor(private bufferTimeSpan: number,
private bufferCreationInterval: number,
private maxBufferSize: number,
private scheduler: SchedulerLike) {
}
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferTimeSubscriber(
subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler
));
}
}
class Context<T> {
buffer: T[] = [];
closeAction: Subscription;
}
interface DispatchCreateArg<T> {
bufferTimeSpan: number;
bufferCreationInterval: number;
subscriber: BufferTimeSubscriber<T>;
scheduler: SchedulerLike;
}
interface DispatchCloseArg<T> {
subscriber: BufferTimeSubscriber<T>;
context: Context<T>;
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferTimeSubscriber<T> extends Subscriber<T> {
private contexts: Array<Context<T>> = [];
private timespanOnly: boolean;
constructor(destination: Subscriber<T[]>,
private bufferTimeSpan: number,
private bufferCreationInterval: number,
private maxBufferSize: number,
private scheduler: SchedulerLike) {
super(destination);
const context = this.openContext();
this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
if (this.timespanOnly) {
const timeSpanOnlyState = { subscriber: this, context, bufferTimeSpan };
this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
} else {
const closeState = { subscriber: this, context };
const creationState: DispatchCreateArg<T> = { bufferTimeSpan, bufferCreationInterval, subscriber: this, scheduler };
this.add(context.closeAction = scheduler.schedule<DispatchCloseArg<T>>(dispatchBufferClose, bufferTimeSpan, closeState));
this.add(scheduler.schedule<DispatchCreateArg<T>>(dispatchBufferCreation, bufferCreationInterval, creationState));
}
}
protected _next(value: T) {
const contexts = this.contexts;
const len = contexts.length;
let filledBufferContext: Context<T>;
for (let i = 0; i < len; i++) {
const context = contexts[i];
const buffer = context.buffer;
buffer.push(value);
if (buffer.length == this.maxBufferSize) {
filledBufferContext = context;
}
}
if (filledBufferContext) {
this.onBufferFull(filledBufferContext);
}
}
protected _error(err: any) {
this.contexts.length = 0;
super._error(err);
}
protected _complete() {
const { contexts, destination } = this;
while (contexts.length > 0) {
const context = contexts.shift();
destination.next(context.buffer);
}
super._complete();
}
/** @deprecated This is an internal implementation detail, do not use. */
_unsubscribe() {
this.contexts = null;
}
protected onBufferFull(context: Context<T>) {
this.closeContext(context);
const closeAction = context.closeAction;
closeAction.unsubscribe();
this.remove(closeAction);
if (!this.closed && this.timespanOnly) {
context = this.openContext();
const bufferTimeSpan = this.bufferTimeSpan;
const timeSpanOnlyState = { subscriber: this, context, bufferTimeSpan };
this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
}
}
openContext(): Context<T> {
const context: Context<T> = new Context<T>();
this.contexts.push(context);
return context;
}
closeContext(context: Context<T>) {
this.destination.next(context.buffer);
const contexts = this.contexts;
const spliceIndex = contexts ? contexts.indexOf(context) : -1;
if (spliceIndex >= 0) {
contexts.splice(contexts.indexOf(context), 1);
}
}
}
function dispatchBufferTimeSpanOnly(this: SchedulerAction<any>, state: any) {
const subscriber: BufferTimeSubscriber<any> = state.subscriber;
const prevContext = state.context;
if (prevContext) {
subscriber.closeContext(prevContext);
}
if (!subscriber.closed) {
state.context = subscriber.openContext();
state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
}
}
function dispatchBufferCreation<T>(this: SchedulerAction<DispatchCreateArg<T>>, state: DispatchCreateArg<T>) {
const { bufferCreationInterval, bufferTimeSpan, subscriber, scheduler } = state;
const context = subscriber.openContext();
const action = <SchedulerAction<DispatchCreateArg<T>>>this;
if (!subscriber.closed) {
subscriber.add(context.closeAction = scheduler.schedule<DispatchCloseArg<T>>(dispatchBufferClose, bufferTimeSpan, { subscriber, context }));
action.schedule(state, bufferCreationInterval);
}
}
function dispatchBufferClose<T>(arg: DispatchCloseArg<T>) {
const { subscriber, context } = arg;
subscriber.closeContext(context);
}

View File

@ -0,0 +1,182 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { Subscription } from '../Subscription';
import { subscribeToResult } from '../util/subscribeToResult';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { OperatorFunction, SubscribableOrPromise } from '../types';
/**
* Buffers the source Observable values starting from an emission from
* `openings` and ending when the output of `closingSelector` emits.
*
* <span class="informal">Collects values from the past as an array. Starts
* collecting only when `opening` emits, and calls the `closingSelector`
* function to get an Observable that tells when to close the buffer.</span>
*
* ![](bufferToggle.png)
*
* Buffers values from the source by opening the buffer via signals from an
* Observable provided to `openings`, and closing and sending the buffers when
* a Subscribable or Promise returned by the `closingSelector` function emits.
*
* ## Example
*
* Every other second, emit the click events from the next 500ms
*
* ```ts
* import { fromEvent, interval, EMPTY } from 'rxjs';
* import { bufferToggle } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const openings = interval(1000);
* const buffered = clicks.pipe(bufferToggle(openings, i =>
* i % 2 ? interval(500) : EMPTY
* ));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link buffer}
* @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferWhen}
* @see {@link windowToggle}
*
* @param {SubscribableOrPromise<O>} openings A Subscribable or Promise of notifications to start new
* buffers.
* @param {function(value: O): SubscribableOrPromise} closingSelector A function that takes
* the value emitted by the `openings` observable and returns a Subscribable or Promise,
* which, when it emits, signals that the associated buffer should be emitted
* and cleared.
* @return {Observable<T[]>} An observable of arrays of buffered values.
* @method bufferToggle
* @owner Observable
*/
export function bufferToggle<T, O>(
openings: SubscribableOrPromise<O>,
closingSelector: (value: O) => SubscribableOrPromise<any>
): OperatorFunction<T, T[]> {
return function bufferToggleOperatorFunction(source: Observable<T>) {
return source.lift(new BufferToggleOperator<T, O>(openings, closingSelector));
};
}
class BufferToggleOperator<T, O> implements Operator<T, T[]> {
constructor(private openings: SubscribableOrPromise<O>,
private closingSelector: (value: O) => SubscribableOrPromise<any>) {
}
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));
}
}
interface BufferContext<T> {
buffer: T[];
subscription: Subscription;
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferToggleSubscriber<T, O> extends OuterSubscriber<T, O> {
private contexts: Array<BufferContext<T>> = [];
constructor(destination: Subscriber<T[]>,
private openings: SubscribableOrPromise<O>,
private closingSelector: (value: O) => SubscribableOrPromise<any> | void) {
super(destination);
this.add(subscribeToResult(this, openings));
}
protected _next(value: T): void {
const contexts = this.contexts;
const len = contexts.length;
for (let i = 0; i < len; i++) {
contexts[i].buffer.push(value);
}
}
protected _error(err: any): void {
const contexts = this.contexts;
while (contexts.length > 0) {
const context = contexts.shift();
context.subscription.unsubscribe();
context.buffer = null;
context.subscription = null;
}
this.contexts = null;
super._error(err);
}
protected _complete(): void {
const contexts = this.contexts;
while (contexts.length > 0) {
const context = contexts.shift();
this.destination.next(context.buffer);
context.subscription.unsubscribe();
context.buffer = null;
context.subscription = null;
}
this.contexts = null;
super._complete();
}
notifyNext(outerValue: any, innerValue: O,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, O>): void {
outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);
}
notifyComplete(innerSub: InnerSubscriber<T, O>): void {
this.closeBuffer((<any> innerSub).context);
}
private openBuffer(value: O): void {
try {
const closingSelector = this.closingSelector;
const closingNotifier = closingSelector.call(this, value);
if (closingNotifier) {
this.trySubscribe(closingNotifier);
}
} catch (err) {
this._error(err);
}
}
private closeBuffer(context: BufferContext<T>): void {
const contexts = this.contexts;
if (contexts && context) {
const { buffer, subscription } = context;
this.destination.next(buffer);
contexts.splice(contexts.indexOf(context), 1);
this.remove(subscription);
subscription.unsubscribe();
}
}
private trySubscribe(closingNotifier: any): void {
const contexts = this.contexts;
const buffer: Array<T> = [];
const subscription = new Subscription();
const context = { buffer, subscription };
contexts.push(context);
const innerSubscription = subscribeToResult(this, closingNotifier, <any>context);
if (!innerSubscription || innerSubscription.closed) {
this.closeBuffer(context);
} else {
(<any> innerSubscription).context = context;
this.add(innerSubscription);
subscription.add(innerSubscription);
}
}
}

144
node_modules/rxjs/src/internal/operators/bufferWhen.ts generated vendored Normal file
View File

@ -0,0 +1,144 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { Subscription } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { OperatorFunction } from '../types';
/**
* Buffers the source Observable values, using a factory function of closing
* Observables to determine when to close, emit, and reset the buffer.
*
* <span class="informal">Collects values from the past as an array. When it
* starts collecting values, it calls a function that returns an Observable that
* tells when to close the buffer and restart collecting.</span>
*
* ![](bufferWhen.png)
*
* Opens a buffer immediately, then closes the buffer when the observable
* returned by calling `closingSelector` function emits a value. When it closes
* the buffer, it immediately opens a new buffer and repeats the process.
*
* ## Example
*
* Emit an array of the last clicks every [1-5] random seconds
*
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { bufferWhen } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferWhen(() =>
* interval(1000 + Math.random() * 4000)
* ));
* buffered.subscribe(x => console.log(x));
* ```
*
*
* @see {@link buffer}
* @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link windowWhen}
*
* @param {function(): Observable} closingSelector A function that takes no
* arguments and returns an Observable that signals buffer closure.
* @return {Observable<T[]>} An observable of arrays of buffered values.
* @method bufferWhen
* @owner Observable
*/
export function bufferWhen<T>(closingSelector: () => Observable<any>): OperatorFunction<T, T[]> {
return function (source: Observable<T>) {
return source.lift(new BufferWhenOperator(closingSelector));
};
}
class BufferWhenOperator<T> implements Operator<T, T[]> {
constructor(private closingSelector: () => Observable<any>) {
}
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class BufferWhenSubscriber<T> extends OuterSubscriber<T, any> {
private buffer: T[];
private subscribing: boolean = false;
private closingSubscription: Subscription;
constructor(destination: Subscriber<T[]>, private closingSelector: () => Observable<any>) {
super(destination);
this.openBuffer();
}
protected _next(value: T) {
this.buffer.push(value);
}
protected _complete() {
const buffer = this.buffer;
if (buffer) {
this.destination.next(buffer);
}
super._complete();
}
/** @deprecated This is an internal implementation detail, do not use. */
_unsubscribe() {
this.buffer = null;
this.subscribing = false;
}
notifyNext(outerValue: T, innerValue: any,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, any>): void {
this.openBuffer();
}
notifyComplete(): void {
if (this.subscribing) {
this.complete();
} else {
this.openBuffer();
}
}
openBuffer() {
let { closingSubscription } = this;
if (closingSubscription) {
this.remove(closingSubscription);
closingSubscription.unsubscribe();
}
const buffer = this.buffer;
if (this.buffer) {
this.destination.next(buffer);
}
this.buffer = [];
let closingNotifier;
try {
const { closingSelector } = this;
closingNotifier = closingSelector();
} catch (err) {
return this.error(err);
}
closingSubscription = new Subscription();
this.closingSubscription = closingSubscription;
this.add(closingSubscription);
this.subscribing = true;
closingSubscription.add(subscribeToResult(this, closingNotifier));
this.subscribing = false;
}
}

149
node_modules/rxjs/src/internal/operators/catchError.ts generated vendored Normal file
View File

@ -0,0 +1,149 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
/* tslint:disable:max-line-length */
export function catchError<T, O extends ObservableInput<any>>(selector: (err: any, caught: Observable<T>) => O): OperatorFunction<T, T | ObservedValueOf<O>>;
/* tslint:enable:max-line-length */
/**
* Catches errors on the observable to be handled by returning a new observable or throwing an error.
*
* ![](catch.png)
*
* ## Examples
* Continues with a different Observable when there's an error
*
* ```ts
* import { of } from 'rxjs';
* import { map, catchError } from 'rxjs/operators';
*
* of(1, 2, 3, 4, 5).pipe(
* map(n => {
* if (n === 4) {
* throw 'four!';
* }
* return n;
* }),
* catchError(err => of('I', 'II', 'III', 'IV', 'V')),
* )
* .subscribe(x => console.log(x));
* // 1, 2, 3, I, II, III, IV, V
* ```
*
* Retries the caught source Observable again in case of error, similar to retry() operator
*
* ```ts
* import { of } from 'rxjs';
* import { map, catchError, take } from 'rxjs/operators';
*
* of(1, 2, 3, 4, 5).pipe(
* map(n => {
* if (n === 4) {
* throw 'four!';
* }
* return n;
* }),
* catchError((err, caught) => caught),
* take(30),
* )
* .subscribe(x => console.log(x));
* // 1, 2, 3, 1, 2, 3, ...
* ```
*
* Throws a new error when the source Observable throws an error
*
* ```ts
* import { of } from 'rxjs';
* import { map, catchError } from 'rxjs/operators';
*
* of(1, 2, 3, 4, 5).pipe(
* map(n => {
* if (n === 4) {
* throw 'four!';
* }
* return n;
* }),
* catchError(err => {
* throw 'error in source. Details: ' + err;
* }),
* )
* .subscribe(
* x => console.log(x),
* err => console.log(err)
* );
* // 1, 2, 3, error in source. Details: four!
* ```
*
* @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
* is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
* is returned by the `selector` will be used to continue the observable chain.
* @return {Observable} An observable that originates from either the source or the observable returned by the
* catch `selector` function.
* @name catchError
*/
export function catchError<T, O extends ObservableInput<any>>(
selector: (err: any, caught: Observable<T>) => O
): OperatorFunction<T, T | ObservedValueOf<O>> {
return function catchErrorOperatorFunction(source: Observable<T>): Observable<T | ObservedValueOf<O>> {
const operator = new CatchOperator(selector);
const caught = source.lift(operator);
return (operator.caught = caught as Observable<T>);
};
}
class CatchOperator<T, R> implements Operator<T, T | R> {
caught: Observable<T>;
constructor(private selector: (err: any, caught: Observable<T>) => ObservableInput<T | R>) {
}
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class CatchSubscriber<T, R> extends OuterSubscriber<T, T | R> {
constructor(destination: Subscriber<any>,
private selector: (err: any, caught: Observable<T>) => ObservableInput<T | R>,
private caught: Observable<T>) {
super(destination);
}
// NOTE: overriding `error` instead of `_error` because we don't want
// to have this flag this subscriber as `isStopped`. We can mimic the
// behavior of the RetrySubscriber (from the `retry` operator), where
// we unsubscribe from our source chain, reset our Subscriber flags,
// then subscribe to the selector result.
error(err: any) {
if (!this.isStopped) {
let result: any;
try {
result = this.selector(err, this.caught);
} catch (err2) {
super.error(err2);
return;
}
this._unsubscribeAndRecycle();
const innerSubscriber = new InnerSubscriber(this, undefined, undefined);
this.add(innerSubscriber);
const innerSubscription = subscribeToResult(this, result, undefined, undefined, innerSubscriber);
// The returned subscription will usually be the subscriber that was
// passed. However, interop subscribers will be wrapped and for
// unsubscriptions to chain correctly, the wrapper needs to be added, too.
if (innerSubscription !== innerSubscriber) {
this.add(innerSubscription);
}
}
}
}

57
node_modules/rxjs/src/internal/operators/combineAll.ts generated vendored Normal file
View File

@ -0,0 +1,57 @@
import { CombineLatestOperator } from '../observable/combineLatest';
import { Observable } from '../Observable';
import { OperatorFunction, ObservableInput } from '../types';
export function combineAll<T>(): OperatorFunction<ObservableInput<T>, T[]>;
export function combineAll<T>(): OperatorFunction<any, T[]>;
export function combineAll<T, R>(project: (...values: T[]) => R): OperatorFunction<ObservableInput<T>, R>;
export function combineAll<R>(project: (...values: Array<any>) => R): OperatorFunction<any, R>;
/**
* Flattens an Observable-of-Observables by applying {@link combineLatest} when the Observable-of-Observables completes.
*
* ![](combineAll.png)
*
* `combineAll` takes an Observable of Observables, and collects all Observables from it. Once the outer Observable completes,
* it subscribes to all collected Observables and combines their values using the {@link combineLatest}</a> strategy, such that:
*
* * Every time an inner Observable emits, the output Observable emits
* * When the returned observable emits, it emits all of the latest values by:
* * If a `project` function is provided, it is called with each recent value from each inner Observable in whatever order they
* arrived, and the result of the `project` function is what is emitted by the output Observable.
* * If there is no `project` function, an array of all the most recent values is emitted by the output Observable.
*
* ---
*
* ## Examples
*
* ### Map two click events to a finite interval Observable, then apply `combineAll`
*
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { map, combineAll, take } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const higherOrder = clicks.pipe(
* map(ev =>
* interval(Math.random() * 2000).pipe(take(3))
* ),
* take(2)
* );
* const result = higherOrder.pipe(
* combineAll()
* );
*
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link combineLatest}
* @see {@link mergeAll}
*
* @param {function(...values: Array<any>)} An optional function to map the most recent values from each inner Observable into a new result.
* Takes each of the most recent values from each collected inner Observable as arguments, in order.
* @return {Observable<T>}
* @name combineAll
*/
export function combineAll<T, R>(project?: (...values: Array<any>) => R): OperatorFunction<T, R> {
return (source: Observable<T>) => source.lift(new CombineLatestOperator(project));
}

View File

@ -0,0 +1,59 @@
import { isArray } from '../util/isArray';
import { CombineLatestOperator } from '../observable/combineLatest';
import { from } from '../observable/from';
import { Observable } from '../Observable';
import { ObservableInput, OperatorFunction } from '../types';
const none = {};
/* tslint:disable:max-line-length */
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, R>(project: (v1: T) => R): OperatorFunction<T, R>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, R>(v2: ObservableInput<T2>, project: (v1: T, v2: T2) => R): OperatorFunction<T, R>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, T3, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, project: (v1: T, v2: T2, v3: T3) => R): OperatorFunction<T, R>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, T3, T4, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, project: (v1: T, v2: T2, v3: T3, v4: T4) => R): OperatorFunction<T, R>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, T3, T4, T5, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => R): OperatorFunction<T, R>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, T3, T4, T5, T6, R>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => R): OperatorFunction<T, R> ;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2>(v2: ObservableInput<T2>): OperatorFunction<T, [T, T2]>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>): OperatorFunction<T, [T, T2, T3]>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): OperatorFunction<T, [T, T2, T3, T4]>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): OperatorFunction<T, [T, T2, T3, T4, T5]>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): OperatorFunction<T, [T, T2, T3, T4, T5, T6]> ;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, R>(...observables: Array<ObservableInput<T> | ((...values: Array<T>) => R)>): OperatorFunction<T, R>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, R>(array: ObservableInput<T>[]): OperatorFunction<T, Array<T>>;
/** @deprecated Deprecated in favor of static combineLatest. */
export function combineLatest<T, TOther, R>(array: ObservableInput<TOther>[], project: (v1: T, ...values: Array<TOther>) => R): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* @deprecated Deprecated in favor of static {@link combineLatest}.
*/
export function combineLatest<T, R>(...observables: Array<ObservableInput<any> |
Array<ObservableInput<any>> |
((...values: Array<any>) => R)>): OperatorFunction<T, R> {
let project: (...values: Array<any>) => R = null;
if (typeof observables[observables.length - 1] === 'function') {
project = <(...values: Array<any>) => R>observables.pop();
}
// if the first and only other argument besides the resultSelector is an array
// assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
if (observables.length === 1 && isArray(observables[0])) {
observables = (<any>observables[0]).slice();
}
return (source: Observable<T>) => source.lift.call(from([source, ...observables]), new CombineLatestOperator(project));
}

29
node_modules/rxjs/src/internal/operators/concat.ts generated vendored Normal file
View File

@ -0,0 +1,29 @@
import { concat as concatStatic } from '../observable/concat';
import { Observable } from '../Observable';
import { ObservableInput, OperatorFunction, MonoTypeOperatorFunction, SchedulerLike } from '../types';
/* tslint:disable:max-line-length */
/** @deprecated Deprecated in favor of static concat. */
export function concat<T>(scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;
/** @deprecated Deprecated in favor of static concat. */
export function concat<T, T2>(v2: ObservableInput<T2>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2>;
/** @deprecated Deprecated in favor of static concat. */
export function concat<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3>;
/** @deprecated Deprecated in favor of static concat. */
export function concat<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4>;
/** @deprecated Deprecated in favor of static concat. */
export function concat<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5>;
/** @deprecated Deprecated in favor of static concat. */
export function concat<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6>;
/** @deprecated Deprecated in favor of static concat. */
export function concat<T>(...observables: Array<ObservableInput<T> | SchedulerLike>): MonoTypeOperatorFunction<T>;
/** @deprecated Deprecated in favor of static concat. */
export function concat<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike>): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* @deprecated Deprecated in favor of static {@link concat}.
*/
export function concat<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike>): OperatorFunction<T, R> {
return (source: Observable<T>) => source.lift.call(concatStatic(source, ...observables));
}

68
node_modules/rxjs/src/internal/operators/concatAll.ts generated vendored Normal file
View File

@ -0,0 +1,68 @@
import { mergeAll } from './mergeAll';
import { OperatorFunction, ObservableInput } from '../types';
export function concatAll<T>(): OperatorFunction<ObservableInput<T>, T>;
export function concatAll<R>(): OperatorFunction<any, R>;
/**
* Converts a higher-order Observable into a first-order Observable by
* concatenating the inner Observables in order.
*
* <span class="informal">Flattens an Observable-of-Observables by putting one
* inner Observable after the other.</span>
*
* ![](concatAll.png)
*
* Joins every Observable emitted by the source (a higher-order Observable), in
* a serial fashion. It subscribes to each inner Observable only after the
* previous inner Observable has completed, and merges all of their values into
* the returned observable.
*
* __Warning:__ If the source Observable emits Observables quickly and
* endlessly, and the inner Observables it emits generally complete slower than
* the source emits, you can run into memory issues as the incoming Observables
* collect in an unbounded buffer.
*
* Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set
* to `1`.
*
* ## Example
*
* For each click event, tick every second from 0 to 3, with no concurrency
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { map, take, concatAll } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const higherOrder = clicks.pipe(
* map(ev => interval(1000).pipe(take(4))),
* );
* const firstOrder = higherOrder.pipe(concatAll());
* firstOrder.subscribe(x => console.log(x));
*
* // Results in the following:
* // (results are not concurrent)
* // For every click on the "document" it will emit values 0 to 3 spaced
* // on a 1000ms interval
* // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
* ```
*
* @see {@link combineAll}
* @see {@link concat}
* @see {@link concatMap}
* @see {@link concatMapTo}
* @see {@link exhaust}
* @see {@link mergeAll}
* @see {@link switchAll}
* @see {@link switchMap}
* @see {@link zipAll}
*
* @return {Observable} An Observable emitting values from all the inner
* Observables concatenated.
* @method concatAll
* @owner Observable
*/
export function concatAll<T>(): OperatorFunction<ObservableInput<T>, T> {
return mergeAll<T>(1);
}

77
node_modules/rxjs/src/internal/operators/concatMap.ts generated vendored Normal file
View File

@ -0,0 +1,77 @@
import { mergeMap } from './mergeMap';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
/* tslint:disable:max-line-length */
export function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated resultSelector no longer supported, use inner map instead */
export function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated resultSelector no longer supported, use inner map instead */
export function concatMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable, in a serialized fashion waiting for each one to complete before
* merging the next.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link concatAll}.</span>
*
* ![](concatMap.png)
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an (so-called "inner") Observable. Each new inner Observable is
* concatenated with the previous inner Observable.
*
* __Warning:__ if source values arrive endlessly and faster than their
* corresponding inner Observables can complete, it will result in memory issues
* as inner Observables amass in an unbounded buffer waiting for their turn to
* be subscribed to.
*
* Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set
* to `1`.
*
* ## Example
* For each click event, tick every second from 0 to 3, with no concurrency
*
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { concatMap, take } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(
* concatMap(ev => interval(1000).pipe(take(4)))
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // (results are not concurrent)
* // For every click on the "document" it will emit values 0 to 3 spaced
* // on a 1000ms interval
* // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
* ```
*
* @see {@link concat}
* @see {@link concatAll}
* @see {@link concatMapTo}
* @see {@link exhaustMap}
* @see {@link mergeMap}
* @see {@link switchMap}
*
* @param {function(value: T, ?index: number): ObservableInput} project A function
* that, when applied to an item emitted by the source Observable, returns an
* Observable.
* @return {Observable} An Observable that emits the result of applying the
* projection function (and the optional deprecated `resultSelector`) to each item emitted
* by the source Observable and taking values from each projected inner
* Observable sequentially.
* @method concatMap
* @owner Observable
*/
export function concatMap<T, R, O extends ObservableInput<any>>(
project: (value: T, index: number) => O,
resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
): OperatorFunction<T, ObservedValueOf<O>|R> {
return mergeMap(project, resultSelector, 1);
}

View File

@ -0,0 +1,73 @@
import { concatMap } from './concatMap';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
/* tslint:disable:max-line-length */
export function concatMapTo<T, O extends ObservableInput<any>>(observable: O): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated */
export function concatMapTo<T, O extends ObservableInput<any>>(observable: O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated */
export function concatMapTo<T, R, O extends ObservableInput<any>>(observable: O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* Projects each source value to the same Observable which is merged multiple
* times in a serialized fashion on the output Observable.
*
* <span class="informal">It's like {@link concatMap}, but maps each value
* always to the same inner Observable.</span>
*
* ![](concatMapTo.png)
*
* Maps each source value to the given Observable `innerObservable` regardless
* of the source value, and then flattens those resulting Observables into one
* single Observable, which is the output Observable. Each new `innerObservable`
* instance emitted on the output Observable is concatenated with the previous
* `innerObservable` instance.
*
* __Warning:__ if source values arrive endlessly and faster than their
* corresponding inner Observables can complete, it will result in memory issues
* as inner Observables amass in an unbounded buffer waiting for their turn to
* be subscribed to.
*
* Note: `concatMapTo` is equivalent to `mergeMapTo` with concurrency parameter
* set to `1`.
*
* ## Example
* For each click event, tick every second from 0 to 3, with no concurrency
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { concatMapTo, take } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(
* concatMapTo(interval(1000).pipe(take(4))),
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // (results are not concurrent)
* // For every click on the "document" it will emit values 0 to 3 spaced
* // on a 1000ms interval
* // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
* ```
*
* @see {@link concat}
* @see {@link concatAll}
* @see {@link concatMap}
* @see {@link mergeMapTo}
* @see {@link switchMapTo}
*
* @param {ObservableInput} innerObservable An Observable to replace each value from
* the source Observable.
* @return {Observable} An observable of values merged together by joining the
* passed observable with itself, one after the other, for each value emitted
* from the source.
* @method concatMapTo
* @owner Observable
*/
export function concatMapTo<T, R, O extends ObservableInput<any>>(
innerObservable: O,
resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
): OperatorFunction<T, ObservedValueOf<O>|R> {
return concatMap(() => innerObservable, resultSelector);
}

121
node_modules/rxjs/src/internal/operators/count.ts generated vendored Normal file
View File

@ -0,0 +1,121 @@
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Observer, OperatorFunction } from '../types';
import { Subscriber } from '../Subscriber';
/**
* Counts the number of emissions on the source and emits that number when the
* source completes.
*
* <span class="informal">Tells how many values were emitted, when the source
* completes.</span>
*
* ![](count.png)
*
* `count` transforms an Observable that emits values into an Observable that
* emits a single value that represents the number of values emitted by the
* source Observable. If the source Observable terminates with an error, `count`
* will pass this error notification along without emitting a value first. If
* the source Observable does not terminate at all, `count` will neither emit
* a value nor terminate. This operator takes an optional `predicate` function
* as argument, in which case the output emission will represent the number of
* source values that matched `true` with the `predicate`.
*
* ## Examples
*
* Counts how many seconds have passed before the first click happened
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { count, takeUntil } from 'rxjs/operators';
*
* const seconds = interval(1000);
* const clicks = fromEvent(document, 'click');
* const secondsBeforeClick = seconds.pipe(takeUntil(clicks));
* const result = secondsBeforeClick.pipe(count());
* result.subscribe(x => console.log(x));
* ```
*
* Counts how many odd numbers are there between 1 and 7
* ```ts
* import { range } from 'rxjs';
* import { count } from 'rxjs/operators';
*
* const numbers = range(1, 7);
* const result = numbers.pipe(count(i => i % 2 === 1));
* result.subscribe(x => console.log(x));
* // Results in:
* // 4
* ```
*
* @see {@link max}
* @see {@link min}
* @see {@link reduce}
*
* @param {function(value: T, i: number, source: Observable<T>): boolean} [predicate] A
* boolean function to select what values are to be counted. It is provided with
* arguments of:
* - `value`: the value from the source Observable.
* - `index`: the (zero-based) "index" of the value from the source Observable.
* - `source`: the source Observable instance itself.
* @return {Observable} An Observable of one number that represents the count as
* described above.
* @method count
* @owner Observable
*/
export function count<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, number> {
return (source: Observable<T>) => source.lift(new CountOperator(predicate, source));
}
class CountOperator<T> implements Operator<T, number> {
constructor(private predicate?: (value: T, index: number, source: Observable<T>) => boolean,
private source?: Observable<T>) {
}
call(subscriber: Subscriber<number>, source: any): any {
return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class CountSubscriber<T> extends Subscriber<T> {
private count: number = 0;
private index: number = 0;
constructor(destination: Observer<number>,
private predicate?: (value: T, index: number, source: Observable<T>) => boolean,
private source?: Observable<T>) {
super(destination);
}
protected _next(value: T): void {
if (this.predicate) {
this._tryPredicate(value);
} else {
this.count++;
}
}
private _tryPredicate(value: T) {
let result: any;
try {
result = this.predicate(value, this.index++, this.source);
} catch (err) {
this.destination.error(err);
return;
}
if (result) {
this.count++;
}
}
protected _complete(): void {
this.destination.next(this.count);
this.destination.complete();
}
}

148
node_modules/rxjs/src/internal/operators/debounce.ts generated vendored Normal file
View File

@ -0,0 +1,148 @@
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { MonoTypeOperatorFunction, SubscribableOrPromise, TeardownLogic } from '../types';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
/**
* Emits a value from the source Observable only after a particular time span
* determined by another Observable has passed without another source emission.
*
* <span class="informal">It's like {@link debounceTime}, but the time span of
* emission silence is determined by a second Observable.</span>
*
* ![](debounce.png)
*
* `debounce` delays values emitted by the source Observable, but drops previous
* pending delayed emissions if a new value arrives on the source Observable.
* This operator keeps track of the most recent value from the source
* Observable, and spawns a duration Observable by calling the
* `durationSelector` function. The value is emitted only when the duration
* Observable emits a value or completes, and if no other value was emitted on
* the source Observable since the duration Observable was spawned. If a new
* value appears before the duration Observable emits, the previous value will
* be dropped and will not be emitted on the output Observable.
*
* Like {@link debounceTime}, this is a rate-limiting operator, and also a
* delay-like operator since output emissions do not necessarily occur at the
* same time as they did on the source Observable.
*
* ## Example
* Emit the most recent click after a burst of clicks
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { debounce } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(debounce(() => interval(1000)));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link audit}
* @see {@link debounceTime}
* @see {@link delayWhen}
* @see {@link throttle}
*
* @param {function(value: T): SubscribableOrPromise} durationSelector A function
* that receives a value from the source Observable, for computing the timeout
* duration for each source value, returned as an Observable or a Promise.
* @return {Observable} An Observable that delays the emissions of the source
* Observable by the specified duration Observable returned by
* `durationSelector`, and may drop some values if they occur too frequently.
* @method debounce
* @owner Observable
*/
export function debounce<T>(durationSelector: (value: T) => SubscribableOrPromise<any>): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => source.lift(new DebounceOperator(durationSelector));
}
class DebounceOperator<T> implements Operator<T, T> {
constructor(private durationSelector: (value: T) => SubscribableOrPromise<any>) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class DebounceSubscriber<T, R> extends OuterSubscriber<T, R> {
private value: T;
private hasValue: boolean = false;
private durationSubscription: Subscription = null;
constructor(destination: Subscriber<R>,
private durationSelector: (value: T) => SubscribableOrPromise<any>) {
super(destination);
}
protected _next(value: T): void {
try {
const result = this.durationSelector.call(this, value);
if (result) {
this._tryNext(value, result);
}
} catch (err) {
this.destination.error(err);
}
}
protected _complete(): void {
this.emitValue();
this.destination.complete();
}
private _tryNext(value: T, duration: SubscribableOrPromise<any>): void {
let subscription = this.durationSubscription;
this.value = value;
this.hasValue = true;
if (subscription) {
subscription.unsubscribe();
this.remove(subscription);
}
subscription = subscribeToResult(this, duration);
if (subscription && !subscription.closed) {
this.add(this.durationSubscription = subscription);
}
}
notifyNext(outerValue: T, innerValue: R,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
this.emitValue();
}
notifyComplete(): void {
this.emitValue();
}
emitValue(): void {
if (this.hasValue) {
const value = this.value;
const subscription = this.durationSubscription;
if (subscription) {
this.durationSubscription = null;
subscription.unsubscribe();
this.remove(subscription);
}
// This must be done *before* passing the value
// along to the destination because it's possible for
// the value to synchronously re-enter this operator
// recursively if the duration selector Observable
// emits synchronously
this.value = null;
this.hasValue = false;
super._next(value);
}
}
}

View File

@ -0,0 +1,130 @@
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { async } from '../scheduler/async';
import { MonoTypeOperatorFunction, SchedulerLike, TeardownLogic } from '../types';
/**
* Emits a value from the source Observable only after a particular time span
* has passed without another source emission.
*
* <span class="informal">It's like {@link delay}, but passes only the most
* recent value from each burst of emissions.</span>
*
* ![](debounceTime.png)
*
* `debounceTime` delays values emitted by the source Observable, but drops
* previous pending delayed emissions if a new value arrives on the source
* Observable. This operator keeps track of the most recent value from the
* source Observable, and emits that only when `dueTime` enough time has passed
* without any other value appearing on the source Observable. If a new value
* appears before `dueTime` silence occurs, the previous value will be dropped
* and will not be emitted on the output Observable.
*
* This is a rate-limiting operator, because it is impossible for more than one
* value to be emitted in any time window of duration `dueTime`, but it is also
* a delay-like operator since output emissions do not occur at the same time as
* they did on the source Observable. Optionally takes a {@link SchedulerLike} for
* managing timers.
*
* ## Example
* Emit the most recent click after a burst of clicks
* ```ts
* import { fromEvent } from 'rxjs';
* import { debounceTime } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(debounceTime(1000));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link auditTime}
* @see {@link debounce}
* @see {@link delay}
* @see {@link sampleTime}
* @see {@link throttleTime}
*
* @param {number} dueTime The timeout duration in milliseconds (or the time
* unit determined internally by the optional `scheduler`) for the window of
* time required to wait for emission silence before emitting the most recent
* source value.
* @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for
* managing the timers that handle the timeout for each value.
* @return {Observable} An Observable that delays the emissions of the source
* Observable by the specified `dueTime`, and may drop some values if they occur
* too frequently.
* @method debounceTime
* @owner Observable
*/
export function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => source.lift(new DebounceTimeOperator(dueTime, scheduler));
}
class DebounceTimeOperator<T> implements Operator<T, T> {
constructor(private dueTime: number, private scheduler: SchedulerLike) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class DebounceTimeSubscriber<T> extends Subscriber<T> {
private debouncedSubscription: Subscription = null;
private lastValue: T = null;
private hasValue: boolean = false;
constructor(destination: Subscriber<T>,
private dueTime: number,
private scheduler: SchedulerLike) {
super(destination);
}
protected _next(value: T) {
this.clearDebounce();
this.lastValue = value;
this.hasValue = true;
this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
}
protected _complete() {
this.debouncedNext();
this.destination.complete();
}
debouncedNext(): void {
this.clearDebounce();
if (this.hasValue) {
const { lastValue } = this;
// This must be done *before* passing the value
// along to the destination because it's possible for
// the value to synchronously re-enter this operator
// recursively when scheduled with things like
// VirtualScheduler/TestScheduler.
this.lastValue = null;
this.hasValue = false;
this.destination.next(lastValue);
}
}
private clearDebounce(): void {
const debouncedSubscription = this.debouncedSubscription;
if (debouncedSubscription !== null) {
this.remove(debouncedSubscription);
debouncedSubscription.unsubscribe();
this.debouncedSubscription = null;
}
}
}
function dispatchNext(subscriber: DebounceTimeSubscriber<any>) {
subscriber.debouncedNext();
}

View File

@ -0,0 +1,84 @@
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { OperatorFunction, MonoTypeOperatorFunction } from '../types';
/* tslint:disable:max-line-length */
export function defaultIfEmpty<T>(defaultValue?: T): MonoTypeOperatorFunction<T>;
export function defaultIfEmpty<T, R>(defaultValue?: R): OperatorFunction<T, T | R>;
/* tslint:enable:max-line-length */
/**
* Emits a given value if the source Observable completes without emitting any
* `next` value, otherwise mirrors the source Observable.
*
* <span class="informal">If the source Observable turns out to be empty, then
* this operator will emit a default value.</span>
*
* ![](defaultIfEmpty.png)
*
* `defaultIfEmpty` emits the values emitted by the source Observable or a
* specified default value if the source Observable is empty (completes without
* having emitted any `next` value).
*
* ## Example
* If no clicks happen in 5 seconds, then emit "no clicks"
* ```ts
* import { fromEvent } from 'rxjs';
* import { defaultIfEmpty, takeUntil } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000)));
* const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link empty}
* @see {@link last}
*
* @param {any} [defaultValue=null] The default value used if the source
* Observable is empty.
* @return {Observable} An Observable that emits either the specified
* `defaultValue` if the source Observable emits no items, or the values emitted
* by the source Observable.
* @method defaultIfEmpty
* @owner Observable
*/
export function defaultIfEmpty<T, R>(defaultValue: R = null): OperatorFunction<T, T | R> {
return (source: Observable<T>) => source.lift(new DefaultIfEmptyOperator(defaultValue)) as Observable<T | R>;
}
class DefaultIfEmptyOperator<T, R> implements Operator<T, T | R> {
constructor(private defaultValue: R) {
}
call(subscriber: Subscriber<T | R>, source: any): any {
return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class DefaultIfEmptySubscriber<T, R> extends Subscriber<T> {
private isEmpty: boolean = true;
constructor(destination: Subscriber<T | R>, private defaultValue: R) {
super(destination);
}
protected _next(value: T): void {
this.isEmpty = false;
this.destination.next(value);
}
protected _complete(): void {
if (this.isEmpty) {
this.destination.next(this.defaultValue);
}
this.destination.complete();
}
}

161
node_modules/rxjs/src/internal/operators/delay.ts generated vendored Normal file
View File

@ -0,0 +1,161 @@
import { async } from '../scheduler/async';
import { isDate } from '../util/isDate';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { Notification } from '../Notification';
import { Observable } from '../Observable';
import { MonoTypeOperatorFunction, PartialObserver, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';
/**
* Delays the emission of items from the source Observable by a given timeout or
* until a given Date.
*
* <span class="informal">Time shifts each item by some specified amount of
* milliseconds.</span>
*
* ![](delay.png)
*
* If the delay argument is a Number, this operator time shifts the source
* Observable by that amount of time expressed in milliseconds. The relative
* time intervals between the values are preserved.
*
* If the delay argument is a Date, this operator time shifts the start of the
* Observable execution until the given date occurs.
*
* ## Examples
* Delay each click by one second
* ```ts
* import { fromEvent } from 'rxjs';
* import { delay } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second
* delayedClicks.subscribe(x => console.log(x));
* ```
*
* Delay all clicks until a future date happens
* ```ts
* import { fromEvent } from 'rxjs';
* import { delay } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const date = new Date('March 15, 2050 12:00:00'); // in the future
* const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date
* delayedClicks.subscribe(x => console.log(x));
* ```
*
* @see {@link debounceTime}
* @see {@link delayWhen}
*
* @param {number|Date} delay The delay duration in milliseconds (a `number`) or
* a `Date` until which the emission of the source items is delayed.
* @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for
* managing the timers that handle the time-shift for each item.
* @return {Observable} An Observable that delays the emissions of the source
* Observable by the specified timeout or Date.
* @method delay
* @owner Observable
*/
export function delay<T>(delay: number|Date,
scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {
const absoluteDelay = isDate(delay);
const delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(<number>delay);
return (source: Observable<T>) => source.lift(new DelayOperator(delayFor, scheduler));
}
class DelayOperator<T> implements Operator<T, T> {
constructor(private delay: number,
private scheduler: SchedulerLike) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
}
}
interface DelayState<T> {
source: DelaySubscriber<T>;
destination: PartialObserver<T>;
scheduler: SchedulerLike;
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class DelaySubscriber<T> extends Subscriber<T> {
private queue: Array<DelayMessage<T>> = [];
private active: boolean = false;
private errored: boolean = false;
private static dispatch<T>(this: SchedulerAction<DelayState<T>>, state: DelayState<T>): void {
const source = state.source;
const queue = source.queue;
const scheduler = state.scheduler;
const destination = state.destination;
while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
queue.shift().notification.observe(destination);
}
if (queue.length > 0) {
const delay = Math.max(0, queue[0].time - scheduler.now());
this.schedule(state, delay);
} else {
this.unsubscribe();
source.active = false;
}
}
constructor(destination: Subscriber<T>,
private delay: number,
private scheduler: SchedulerLike) {
super(destination);
}
private _schedule(scheduler: SchedulerLike): void {
this.active = true;
const destination = this.destination as Subscription;
destination.add(scheduler.schedule<DelayState<T>>(DelaySubscriber.dispatch, this.delay, {
source: this, destination: this.destination, scheduler: scheduler
}));
}
private scheduleNotification(notification: Notification<T>): void {
if (this.errored === true) {
return;
}
const scheduler = this.scheduler;
const message = new DelayMessage(scheduler.now() + this.delay, notification);
this.queue.push(message);
if (this.active === false) {
this._schedule(scheduler);
}
}
protected _next(value: T) {
this.scheduleNotification(Notification.createNext(value));
}
protected _error(err: any) {
this.errored = true;
this.queue = [];
this.destination.error(err);
this.unsubscribe();
}
protected _complete() {
this.scheduleNotification(Notification.createComplete());
this.unsubscribe();
}
}
class DelayMessage<T> {
constructor(public readonly time: number,
public readonly notification: Notification<T>) {
}
}

225
node_modules/rxjs/src/internal/operators/delayWhen.ts generated vendored Normal file
View File

@ -0,0 +1,225 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { Subscription } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
/* tslint:disable:max-line-length */
/** @deprecated In future versions, empty notifiers will no longer re-emit the source value on the output observable. */
export function delayWhen<T>(delayDurationSelector: (value: T, index: number) => Observable<never>, subscriptionDelay?: Observable<any>): MonoTypeOperatorFunction<T>;
export function delayWhen<T>(delayDurationSelector: (value: T, index: number) => Observable<any>, subscriptionDelay?: Observable<any>): MonoTypeOperatorFunction<T>;
/* tslint:disable:max-line-length */
/**
* Delays the emission of items from the source Observable by a given time span
* determined by the emissions of another Observable.
*
* <span class="informal">It's like {@link delay}, but the time span of the
* delay duration is determined by a second Observable.</span>
*
* ![](delayWhen.png)
*
* `delayWhen` time shifts each emitted value from the source Observable by a
* time span determined by another Observable. When the source emits a value,
* the `delayDurationSelector` function is called with the source value as
* argument, and should return an Observable, called the "duration" Observable.
* The source value is emitted on the output Observable only when the duration
* Observable emits a value or completes.
* The completion of the notifier triggering the emission of the source value
* is deprecated behavior and will be removed in future versions.
*
* Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which
* is an Observable. When `subscriptionDelay` emits its first value or
* completes, the source Observable is subscribed to and starts behaving like
* described in the previous paragraph. If `subscriptionDelay` is not provided,
* `delayWhen` will subscribe to the source Observable as soon as the output
* Observable is subscribed.
*
* ## Example
* Delay each click by a random amount of time, between 0 and 5 seconds
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { delayWhen } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const delayedClicks = clicks.pipe(
* delayWhen(event => interval(Math.random() * 5000)),
* );
* delayedClicks.subscribe(x => console.log(x));
* ```
*
* @see {@link delay}
* @see {@link throttle}
* @see {@link throttleTime}
* @see {@link debounce}
* @see {@link debounceTime}
* @see {@link sample}
* @see {@link sampleTime}
* @see {@link audit}
* @see {@link auditTime}
*
* @param {function(value: T, index: number): Observable} delayDurationSelector A function that
* returns an Observable for each value emitted by the source Observable, which
* is then used to delay the emission of that item on the output Observable
* until the Observable returned from this function emits a value.
* @param {Observable} subscriptionDelay An Observable that triggers the
* subscription to the source Observable once it emits any value.
* @return {Observable} An Observable that delays the emissions of the source
* Observable by an amount of time specified by the Observable returned by
* `delayDurationSelector`.
* @method delayWhen
* @owner Observable
*/
export function delayWhen<T>(delayDurationSelector: (value: T, index: number) => Observable<any>,
subscriptionDelay?: Observable<any>): MonoTypeOperatorFunction<T> {
if (subscriptionDelay) {
return (source: Observable<T>) =>
new SubscriptionDelayObservable(source, subscriptionDelay)
.lift(new DelayWhenOperator(delayDurationSelector));
}
return (source: Observable<T>) => source.lift(new DelayWhenOperator(delayDurationSelector));
}
class DelayWhenOperator<T> implements Operator<T, T> {
constructor(private delayDurationSelector: (value: T, index: number) => Observable<any>) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class DelayWhenSubscriber<T, R> extends OuterSubscriber<T, R> {
private completed: boolean = false;
private delayNotifierSubscriptions: Array<Subscription> = [];
private index: number = 0;
constructor(destination: Subscriber<T>,
private delayDurationSelector: (value: T, index: number) => Observable<any>) {
super(destination);
}
notifyNext(outerValue: T, innerValue: any,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
this.destination.next(outerValue);
this.removeSubscription(innerSub);
this.tryComplete();
}
notifyError(error: any, innerSub: InnerSubscriber<T, R>): void {
this._error(error);
}
notifyComplete(innerSub: InnerSubscriber<T, R>): void {
const value = this.removeSubscription(innerSub);
if (value) {
this.destination.next(value);
}
this.tryComplete();
}
protected _next(value: T): void {
const index = this.index++;
try {
const delayNotifier = this.delayDurationSelector(value, index);
if (delayNotifier) {
this.tryDelay(delayNotifier, value);
}
} catch (err) {
this.destination.error(err);
}
}
protected _complete(): void {
this.completed = true;
this.tryComplete();
this.unsubscribe();
}
private removeSubscription(subscription: InnerSubscriber<T, R>): T {
subscription.unsubscribe();
const subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);
if (subscriptionIdx !== -1) {
this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);
}
return subscription.outerValue;
}
private tryDelay(delayNotifier: Observable<any>, value: T): void {
const notifierSubscription = subscribeToResult(this, delayNotifier, value);
if (notifierSubscription && !notifierSubscription.closed) {
const destination = this.destination as Subscription;
destination.add(notifierSubscription);
this.delayNotifierSubscriptions.push(notifierSubscription);
}
}
private tryComplete(): void {
if (this.completed && this.delayNotifierSubscriptions.length === 0) {
this.destination.complete();
}
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class SubscriptionDelayObservable<T> extends Observable<T> {
constructor(public source: Observable<T>, private subscriptionDelay: Observable<any>) {
super();
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>) {
this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class SubscriptionDelaySubscriber<T> extends Subscriber<T> {
private sourceSubscribed: boolean = false;
constructor(private parent: Subscriber<T>, private source: Observable<T>) {
super();
}
protected _next(unused: any) {
this.subscribeToSource();
}
protected _error(err: any) {
this.unsubscribe();
this.parent.error(err);
}
protected _complete() {
this.unsubscribe();
this.subscribeToSource();
}
private subscribeToSource(): void {
if (!this.sourceSubscribed) {
this.sourceSubscribed = true;
this.unsubscribe();
this.source.subscribe(this.parent);
}
}
}

View File

@ -0,0 +1,78 @@
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Notification } from '../Notification';
import { OperatorFunction } from '../types';
/**
* Converts an Observable of {@link Notification} objects into the emissions
* that they represent.
*
* <span class="informal">Unwraps {@link Notification} objects as actual `next`,
* `error` and `complete` emissions. The opposite of {@link materialize}.</span>
*
* ![](dematerialize.png)
*
* `dematerialize` is assumed to operate an Observable that only emits
* {@link Notification} objects as `next` emissions, and does not emit any
* `error`. Such Observable is the output of a `materialize` operation. Those
* notifications are then unwrapped using the metadata they contain, and emitted
* as `next`, `error`, and `complete` on the output Observable.
*
* Use this operator in conjunction with {@link materialize}.
*
* ## Example
* Convert an Observable of Notifications to an actual Observable
* ```ts
* import { of, Notification } from 'rxjs';
* import { dematerialize } from 'rxjs/operators';
*
* const notifA = new Notification('N', 'A');
* const notifB = new Notification('N', 'B');
* const notifE = new Notification('E', undefined,
* new TypeError('x.toUpperCase is not a function')
* );
* const materialized = of(notifA, notifB, notifE);
* const upperCase = materialized.pipe(dematerialize());
* upperCase.subscribe(x => console.log(x), e => console.error(e));
*
* // Results in:
* // A
* // B
* // TypeError: x.toUpperCase is not a function
* ```
*
* @see {@link Notification}
* @see {@link materialize}
*
* @return {Observable} An Observable that emits items and notifications
* embedded in Notification objects emitted by the source Observable.
* @method dematerialize
* @owner Observable
*/
export function dematerialize<T>(): OperatorFunction<Notification<T>, T> {
return function dematerializeOperatorFunction(source: Observable<Notification<T>>) {
return source.lift(new DeMaterializeOperator());
};
}
class DeMaterializeOperator<T extends Notification<any>, R> implements Operator<T, R> {
call(subscriber: Subscriber<any>, source: any): any {
return source.subscribe(new DeMaterializeSubscriber(subscriber));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class DeMaterializeSubscriber<T extends Notification<any>> extends Subscriber<T> {
constructor(destination: Subscriber<any>) {
super(destination);
}
protected _next(value: T) {
value.observe(this.destination);
}
}

135
node_modules/rxjs/src/internal/operators/distinct.ts generated vendored Normal file
View File

@ -0,0 +1,135 @@
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
*
* If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
* check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
* source observable directly with an equality check against previous values.
*
* In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
*
* In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
* hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
* use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
* that the internal `Set` can be "flushed", basically clearing it of values.
*
* ## Examples
* A simple example with numbers
* ```ts
* import { of } from 'rxjs';
* import { distinct } from 'rxjs/operators';
*
* of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1).pipe(
* distinct(),
* )
* .subscribe(x => console.log(x)); // 1, 2, 3, 4
* ```
*
* An example using a keySelector function
* ```typescript
* import { of } from 'rxjs';
* import { distinct } from 'rxjs/operators';
*
* interface Person {
* age: number,
* name: string
* }
*
* of<Person>(
* { age: 4, name: 'Foo'},
* { age: 7, name: 'Bar'},
* { age: 5, name: 'Foo'},
* ).pipe(
* distinct((p: Person) => p.name),
* )
* .subscribe(x => console.log(x));
*
* // displays:
* // { age: 4, name: 'Foo' }
* // { age: 7, name: 'Bar' }
* ```
* @see {@link distinctUntilChanged}
* @see {@link distinctUntilKeyChanged}
*
* @param {function} [keySelector] Optional function to select which value you want to check as distinct.
* @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
* @return {Observable} An Observable that emits items from the source Observable with distinct values.
* @method distinct
* @owner Observable
*/
export function distinct<T, K>(keySelector?: (value: T) => K,
flushes?: Observable<any>): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => source.lift(new DistinctOperator(keySelector, flushes));
}
class DistinctOperator<T, K> implements Operator<T, T> {
constructor(private keySelector: (value: T) => K, private flushes: Observable<any>) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class DistinctSubscriber<T, K> extends OuterSubscriber<T, T> {
private values = new Set<K>();
constructor(destination: Subscriber<T>, private keySelector: (value: T) => K, flushes: Observable<any>) {
super(destination);
if (flushes) {
this.add(subscribeToResult(this, flushes));
}
}
notifyNext(outerValue: T, innerValue: T,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, T>): void {
this.values.clear();
}
notifyError(error: any, innerSub: InnerSubscriber<T, T>): void {
this._error(error);
}
protected _next(value: T): void {
if (this.keySelector) {
this._useKeySelector(value);
} else {
this._finalizeNext(value, value);
}
}
private _useKeySelector(value: T): void {
let key: K;
const { destination } = this;
try {
key = this.keySelector(value);
} catch (err) {
destination.error(err);
return;
}
this._finalizeNext(key, value);
}
private _finalizeNext(key: K|T, value: T) {
const { values } = this;
if (!values.has(<K>key)) {
values.add(<K>key);
this.destination.next(value);
}
}
}

View File

@ -0,0 +1,124 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
/* tslint:disable:max-line-length */
export function distinctUntilChanged<T>(compare?: (x: T, y: T) => boolean): MonoTypeOperatorFunction<T>;
export function distinctUntilChanged<T, K>(compare: (x: K, y: K) => boolean, keySelector: (x: T) => K): MonoTypeOperatorFunction<T>;
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
*
* If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
*
* If a comparator function is not provided, an equality check is used by default.
*
* ## Example
* A simple example with numbers
* ```ts
* import { of } from 'rxjs';
* import { distinctUntilChanged } from 'rxjs/operators';
*
* of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(
* distinctUntilChanged(),
* )
* .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
* ```
*
* An example using a compare function
* ```typescript
* import { of } from 'rxjs';
* import { distinctUntilChanged } from 'rxjs/operators';
*
* interface Person {
* age: number,
* name: string
* }
*
* of<Person>(
* { age: 4, name: 'Foo'},
* { age: 7, name: 'Bar'},
* { age: 5, name: 'Foo'},
* { age: 6, name: 'Foo'},
* ).pipe(
* distinctUntilChanged((p: Person, q: Person) => p.name === q.name),
* )
* .subscribe(x => console.log(x));
*
* // displays:
* // { age: 4, name: 'Foo' }
* // { age: 7, name: 'Bar' }
* // { age: 5, name: 'Foo' }
* ```
*
* @see {@link distinct}
* @see {@link distinctUntilKeyChanged}
*
* @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
* @return {Observable} An Observable that emits items from the source Observable with distinct values.
* @method distinctUntilChanged
* @owner Observable
*/
export function distinctUntilChanged<T, K>(compare?: (x: K, y: K) => boolean, keySelector?: (x: T) => K): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => source.lift(new DistinctUntilChangedOperator<T, K>(compare, keySelector));
}
class DistinctUntilChangedOperator<T, K> implements Operator<T, T> {
constructor(private compare: (x: K, y: K) => boolean,
private keySelector: (x: T) => K) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class DistinctUntilChangedSubscriber<T, K> extends Subscriber<T> {
private key: K;
private hasKey: boolean = false;
constructor(destination: Subscriber<T>,
compare: (x: K, y: K) => boolean,
private keySelector: (x: T) => K) {
super(destination);
if (typeof compare === 'function') {
this.compare = compare;
}
}
private compare(x: any, y: any): boolean {
return x === y;
}
protected _next(value: T): void {
let key: any;
try {
const { keySelector } = this;
key = keySelector ? keySelector(value) : value;
} catch (err) {
return this.destination.error(err);
}
let result = false;
if (this.hasKey) {
try {
const { compare } = this;
result = compare(this.key, key);
} catch (err) {
return this.destination.error(err);
}
} else {
this.hasKey = true;
}
if (!result) {
this.key = key;
this.destination.next(value);
}
}
}

View File

@ -0,0 +1,81 @@
import { distinctUntilChanged } from './distinctUntilChanged';
import { MonoTypeOperatorFunction } from '../types';
/* tslint:disable:max-line-length */
export function distinctUntilKeyChanged<T>(key: keyof T): MonoTypeOperatorFunction<T>;
export function distinctUntilKeyChanged<T, K extends keyof T>(key: K, compare: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction<T>;
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item,
* using a property accessed by using the key provided to check if the two items are distinct.
*
* If a comparator function is provided, then it will be called for each item to test for whether or not that value should be emitted.
*
* If a comparator function is not provided, an equality check is used by default.
*
* ## Examples
* An example comparing the name of persons
* ```typescript
* import { of } from 'rxjs';
* import { distinctUntilKeyChanged } from 'rxjs/operators';
*
* interface Person {
* age: number,
* name: string
* }
*
* of<Person>(
* { age: 4, name: 'Foo'},
* { age: 7, name: 'Bar'},
* { age: 5, name: 'Foo'},
* { age: 6, name: 'Foo'},
* ).pipe(
* distinctUntilKeyChanged('name'),
* )
* .subscribe(x => console.log(x));
*
* // displays:
* // { age: 4, name: 'Foo' }
* // { age: 7, name: 'Bar' }
* // { age: 5, name: 'Foo' }
* ```
*
* An example comparing the first letters of the name
* ```typescript
* import { of } from 'rxjs';
* import { distinctUntilKeyChanged } from 'rxjs/operators';
*
* interface Person {
* age: number,
* name: string
* }
*
* of<Person>(
* { age: 4, name: 'Foo1'},
* { age: 7, name: 'Bar'},
* { age: 5, name: 'Foo2'},
* { age: 6, name: 'Foo3'},
* ).pipe(
* distinctUntilKeyChanged('name', (x: string, y: string) => x.substring(0, 3) === y.substring(0, 3)),
* )
* .subscribe(x => console.log(x));
*
* // displays:
* // { age: 4, name: 'Foo1' }
* // { age: 7, name: 'Bar' }
* // { age: 5, name: 'Foo2' }
* ```
*
* @see {@link distinct}
* @see {@link distinctUntilChanged}
*
* @param {string} key String key for object property lookup on each item.
* @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
* @return {Observable} An Observable that emits items from the source Observable with distinct values based on the key specified.
* @method distinctUntilKeyChanged
* @owner Observable
*/
export function distinctUntilKeyChanged<T, K extends keyof T>(key: K, compare?: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction<T> {
return distinctUntilChanged((x: T, y: T) => compare ? compare(x[key], y[key]) : x[key] === y[key]);
}

69
node_modules/rxjs/src/internal/operators/elementAt.ts generated vendored Normal file
View File

@ -0,0 +1,69 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';
import { Observable } from '../Observable';
import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
import { filter } from './filter';
import { throwIfEmpty } from './throwIfEmpty';
import { defaultIfEmpty } from './defaultIfEmpty';
import { take } from './take';
/**
* Emits the single value at the specified `index` in a sequence of emissions
* from the source Observable.
*
* <span class="informal">Emits only the i-th value, then completes.</span>
*
* ![](elementAt.png)
*
* `elementAt` returns an Observable that emits the item at the specified
* `index` in the source Observable, or a default value if that `index` is out
* of range and the `default` argument is provided. If the `default` argument is
* not given and the `index` is out of range, the output Observable will emit an
* `ArgumentOutOfRangeError` error.
*
* ## Example
* Emit only the third click event
* ```ts
* import { fromEvent } from 'rxjs';
* import { elementAt } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(elementAt(2));
* result.subscribe(x => console.log(x));
*
* // Results in:
* // click 1 = nothing
* // click 2 = nothing
* // click 3 = MouseEvent object logged to console
* ```
*
* @see {@link first}
* @see {@link last}
* @see {@link skip}
* @see {@link single}
* @see {@link take}
*
* @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an
* ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0` or the
* Observable has completed before emitting the i-th `next` notification.
*
* @param {number} index Is the number `i` for the i-th source emission that has
* happened since the subscription, starting from the number `0`.
* @param {T} [defaultValue] The default value returned for missing indices.
* @return {Observable} An Observable that emits a single item, if it is found.
* Otherwise, will emit the default value if given. If not, then emits an error.
* @method elementAt
* @owner Observable
*/
export function elementAt<T>(index: number, defaultValue?: T): MonoTypeOperatorFunction<T> {
if (index < 0) { throw new ArgumentOutOfRangeError(); }
const hasDefaultValue = arguments.length >= 2;
return (source: Observable<T>) => source.pipe(
filter((v, i) => i === index),
take(1),
hasDefaultValue
? defaultIfEmpty(defaultValue)
: throwIfEmpty(() => new ArgumentOutOfRangeError()),
);
}

67
node_modules/rxjs/src/internal/operators/endWith.ts generated vendored Normal file
View File

@ -0,0 +1,67 @@
import { Observable } from '../Observable';
import { concat } from '../observable/concat';
import { of } from '../observable/of';
import { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction } from '../types';
/* tslint:disable:max-line-length */
/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */
export function endWith<T>(scheduler: SchedulerLike): MonoTypeOperatorFunction<T>;
/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */
export function endWith<T, A>(v1: A, scheduler: SchedulerLike): OperatorFunction<T, T | A>;
/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */
export function endWith<T, A, B>(v1: A, v2: B, scheduler: SchedulerLike): OperatorFunction<T, T | A | B>;
/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */
export function endWith<T, A, B, C>(v1: A, v2: B, v3: C, scheduler: SchedulerLike): OperatorFunction<T, T | A | B | C>;
/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */
export function endWith<T, A, B, C, D>(v1: A, v2: B, v3: C, v4: D, scheduler: SchedulerLike): OperatorFunction<T, T | A | B | C | D>;
/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */
export function endWith<T, A, B, C, D, E>(v1: A, v2: B, v3: C, v4: D, v5: E, scheduler: SchedulerLike): OperatorFunction<T, T | A | B | C | D | E>;
/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */
export function endWith<T, A, B, C, D, E, F>(v1: A, v2: B, v3: C, v4: D, v5: E, v6: F, scheduler: SchedulerLike): OperatorFunction<T, T | A | B | C | D | E | F>;
export function endWith<T, A>(v1: A): OperatorFunction<T, T | A>;
export function endWith<T, A, B>(v1: A, v2: B): OperatorFunction<T, T | A | B>;
export function endWith<T, A, B, C>(v1: A, v2: B, v3: C): OperatorFunction<T, T | A | B | C>;
export function endWith<T, A, B, C, D>(v1: A, v2: B, v3: C, v4: D): OperatorFunction<T, T | A | B | C | D>;
export function endWith<T, A, B, C, D, E>(v1: A, v2: B, v3: C, v4: D, v5: E): OperatorFunction<T, T | A | B | C | D | E>;
export function endWith<T, A, B, C, D, E, F>(v1: A, v2: B, v3: C, v4: D, v5: E, v6: F): OperatorFunction<T, T | A | B | C | D | E | F>;
export function endWith<T, Z = T>(...array: Z[]): OperatorFunction<T, T | Z>;
/** @deprecated use {@link scheduled} and {@link concatAll} (e.g. `scheduled([source, [a, b, c]], scheduler).pipe(concatAll())`) */
export function endWith<T, Z = T>(...array: Array<Z | SchedulerLike>): OperatorFunction<T, T | Z>;
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits the items you specify as arguments after it finishes emitting
* items emitted by the source Observable.
*
* ![](endWith.png)
*
* ## Example
* ### After the source observable completes, appends an emission and then completes too.
*
* ```ts
* import { of } from 'rxjs';
* import { endWith } from 'rxjs/operators';
*
* of('hi', 'how are you?', 'sorry, I have to go now').pipe(
* endWith('goodbye!'),
* )
* .subscribe(word => console.log(word));
* // result:
* // 'hi'
* // 'how are you?'
* // 'sorry, I have to go now'
* // 'goodbye!'
* ```
*
* @param {...T} values - Items you want the modified Observable to emit last.
* @param {SchedulerLike} [scheduler] - A {@link SchedulerLike} to use for scheduling
* the emissions of the `next` notifications.
* @return {Observable} An Observable that emits the items emitted by the source Observable
* and then emits the items in the specified Iterable.
* @method endWith
* @owner Observable
*/
export function endWith<T>(...array: Array<T | SchedulerLike>): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => concat(source, of(...array)) as Observable<T>;
}

81
node_modules/rxjs/src/internal/operators/every.ts generated vendored Normal file
View File

@ -0,0 +1,81 @@
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Observer, OperatorFunction } from '../types';
/**
* Returns an Observable that emits whether or not every item of the source satisfies the condition specified.
*
* ## Example
* A simple example emitting true if all elements are less than 5, false otherwise
* ```ts
* import { of } from 'rxjs';
* import { every } from 'rxjs/operators';
*
* of(1, 2, 3, 4, 5, 6).pipe(
* every(x => x < 5),
* )
* .subscribe(x => console.log(x)); // -> false
* ```
*
* @param {function} predicate A function for determining if an item meets a specified condition.
* @param {any} [thisArg] Optional object to use for `this` in the callback.
* @return {Observable} An Observable of booleans that determines if all items of the source Observable meet the condition specified.
* @method every
* @owner Observable
*/
export function every<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,
thisArg?: any): OperatorFunction<T, boolean> {
return (source: Observable<T>) => source.lift(new EveryOperator(predicate, thisArg, source));
}
class EveryOperator<T> implements Operator<T, boolean> {
constructor(private predicate: (value: T, index: number, source: Observable<T>) => boolean,
private thisArg?: any,
private source?: Observable<T>) {
}
call(observer: Subscriber<boolean>, source: any): any {
return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class EverySubscriber<T> extends Subscriber<T> {
private index: number = 0;
constructor(destination: Observer<boolean>,
private predicate: (value: T, index: number, source: Observable<T>) => boolean,
private thisArg: any,
private source?: Observable<T>) {
super(destination);
this.thisArg = thisArg || this;
}
private notifyComplete(everyValueMatch: boolean): void {
this.destination.next(everyValueMatch);
this.destination.complete();
}
protected _next(value: T): void {
let result = false;
try {
result = this.predicate.call(this.thisArg, value, this.index++, this.source);
} catch (err) {
this.destination.error(err);
return;
}
if (!result) {
this.notifyComplete(false);
}
}
protected _complete(): void {
this.notifyComplete(true);
}
}

100
node_modules/rxjs/src/internal/operators/exhaust.ts generated vendored Normal file
View File

@ -0,0 +1,100 @@
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { ObservableInput, OperatorFunction, TeardownLogic } from '../types';
export function exhaust<T>(): OperatorFunction<ObservableInput<T>, T>;
export function exhaust<R>(): OperatorFunction<any, R>;
/**
* Converts a higher-order Observable into a first-order Observable by dropping
* inner Observables while the previous inner Observable has not yet completed.
*
* <span class="informal">Flattens an Observable-of-Observables by dropping the
* next inner Observables while the current inner is still executing.</span>
*
* ![](exhaust.png)
*
* `exhaust` subscribes to an Observable that emits Observables, also known as a
* higher-order Observable. Each time it observes one of these emitted inner
* Observables, the output Observable begins emitting the items emitted by that
* inner Observable. So far, it behaves like {@link mergeAll}. However,
* `exhaust` ignores every new inner Observable if the previous Observable has
* not yet completed. Once that one completes, it will accept and flatten the
* next inner Observable and repeat this process.
*
* ## Example
* Run a finite timer for each click, only if there is no currently active timer
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { exhaust, map, take } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const higherOrder = clicks.pipe(
* map((ev) => interval(1000).pipe(take(5))),
* );
* const result = higherOrder.pipe(exhaust());
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link combineAll}
* @see {@link concatAll}
* @see {@link switchAll}
* @see {@link switchMap}
* @see {@link mergeAll}
* @see {@link exhaustMap}
* @see {@link zipAll}
*
* @return {Observable} An Observable that takes a source of Observables and propagates the first observable
* exclusively until it completes before subscribing to the next.
* @method exhaust
* @owner Observable
*/
export function exhaust<T>(): OperatorFunction<any, T> {
return (source: Observable<T>) => source.lift(new SwitchFirstOperator<T>());
}
class SwitchFirstOperator<T> implements Operator<T, T> {
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new SwitchFirstSubscriber(subscriber));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class SwitchFirstSubscriber<T> extends OuterSubscriber<T, T> {
private hasCompleted: boolean = false;
private hasSubscription: boolean = false;
constructor(destination: Subscriber<T>) {
super(destination);
}
protected _next(value: T): void {
if (!this.hasSubscription) {
this.hasSubscription = true;
this.add(subscribeToResult(this, value));
}
}
protected _complete(): void {
this.hasCompleted = true;
if (!this.hasSubscription) {
this.destination.complete();
}
}
notifyComplete(innerSub: Subscription): void {
this.remove(innerSub);
this.hasSubscription = false;
if (this.hasCompleted) {
this.destination.complete();
}
}
}

164
node_modules/rxjs/src/internal/operators/exhaustMap.ts generated vendored Normal file
View File

@ -0,0 +1,164 @@
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
import { map } from './map';
import { from } from '../observable/from';
/* tslint:disable:max-line-length */
export function exhaustMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated resultSelector is no longer supported. Use inner map instead. */
export function exhaustMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated resultSelector is no longer supported. Use inner map instead. */
export function exhaustMap<T, I, R>(project: (value: T, index: number) => ObservableInput<I>, resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable only if the previous projected Observable has completed.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link exhaust}.</span>
*
* ![](exhaustMap.png)
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an (so-called "inner") Observable. When it projects a source value to
* an Observable, the output Observable begins emitting the items emitted by
* that projected Observable. However, `exhaustMap` ignores every new projected
* Observable if the previous projected Observable has not yet completed. Once
* that one completes, it will accept and flatten the next projected Observable
* and repeat this process.
*
* ## Example
* Run a finite timer for each click, only if there is no currently active timer
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { exhaustMap, take } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(
* exhaustMap(ev => interval(1000).pipe(take(5)))
* );
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link concatMap}
* @see {@link exhaust}
* @see {@link mergeMap}
* @see {@link switchMap}
*
* @param {function(value: T, ?index: number): ObservableInput} project A function
* that, when applied to an item emitted by the source Observable, returns an
* Observable.
* @return {Observable} An Observable containing projected Observables
* of each item of the source, ignoring projected Observables that start before
* their preceding Observable has completed.
* @method exhaustMap
* @owner Observable
*/
export function exhaustMap<T, R, O extends ObservableInput<any>>(
project: (value: T, index: number) => O,
resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,
): OperatorFunction<T, ObservedValueOf<O>|R> {
if (resultSelector) {
// DEPRECATED PATH
return (source: Observable<T>) => source.pipe(
exhaustMap((a, i) => from(project(a, i)).pipe(
map((b: any, ii: any) => resultSelector(a, b, i, ii)),
)),
);
}
return (source: Observable<T>) =>
source.lift(new ExhaustMapOperator(project));
}
class ExhaustMapOperator<T, R> implements Operator<T, R> {
constructor(private project: (value: T, index: number) => ObservableInput<R>) {
}
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class ExhaustMapSubscriber<T, R> extends OuterSubscriber<T, R> {
private hasSubscription = false;
private hasCompleted = false;
private index = 0;
constructor(destination: Subscriber<R>,
private project: (value: T, index: number) => ObservableInput<R>) {
super(destination);
}
protected _next(value: T): void {
if (!this.hasSubscription) {
this.tryNext(value);
}
}
private tryNext(value: T): void {
let result: ObservableInput<R>;
const index = this.index++;
try {
result = this.project(value, index);
} catch (err) {
this.destination.error(err);
return;
}
this.hasSubscription = true;
this._innerSub(result, value, index);
}
private _innerSub(result: ObservableInput<R>, value: T, index: number): void {
const innerSubscriber = new InnerSubscriber(this, value, index);
const destination = this.destination as Subscription;
destination.add(innerSubscriber);
const innerSubscription = subscribeToResult<T, R>(this, result, undefined, undefined, innerSubscriber);
// The returned subscription will usually be the subscriber that was
// passed. However, interop subscribers will be wrapped and for
// unsubscriptions to chain correctly, the wrapper needs to be added, too.
if (innerSubscription !== innerSubscriber) {
destination.add(innerSubscription);
}
}
protected _complete(): void {
this.hasCompleted = true;
if (!this.hasSubscription) {
this.destination.complete();
}
this.unsubscribe();
}
notifyNext(outerValue: T, innerValue: R,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
this.destination.next(innerValue);
}
notifyError(err: any): void {
this.destination.error(err);
}
notifyComplete(innerSub: Subscription): void {
const destination = this.destination as Subscription;
destination.remove(innerSub);
this.hasSubscription = false;
if (this.hasCompleted) {
this.destination.complete();
}
}
}

180
node_modules/rxjs/src/internal/operators/expand.ts generated vendored Normal file
View File

@ -0,0 +1,180 @@
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { MonoTypeOperatorFunction, OperatorFunction, ObservableInput, SchedulerLike } from '../types';
/* tslint:disable:max-line-length */
export function expand<T, R>(project: (value: T, index: number) => ObservableInput<R>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, R>;
export function expand<T>(project: (value: T, index: number) => ObservableInput<T>, concurrent?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;
/* tslint:enable:max-line-length */
/**
* Recursively projects each source value to an Observable which is merged in
* the output Observable.
*
* <span class="informal">It's similar to {@link mergeMap}, but applies the
* projection function to every source value as well as every output value.
* It's recursive.</span>
*
* ![](expand.png)
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an Observable, and then merging those resulting Observables and
* emitting the results of this merger. *Expand* will re-emit on the output
* Observable every source value. Then, each output value is given to the
* `project` function which returns an inner Observable to be merged on the
* output Observable. Those output values resulting from the projection are also
* given to the `project` function to produce new output values. This is how
* *expand* behaves recursively.
*
* ## Example
* Start emitting the powers of two on every click, at most 10 of them
* ```ts
* import { fromEvent, of } from 'rxjs';
* import { expand, mapTo, delay, take } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const powersOfTwo = clicks.pipe(
* mapTo(1),
* expand(x => of(2 * x).pipe(delay(1000))),
* take(10),
* );
* powersOfTwo.subscribe(x => console.log(x));
* ```
*
* @see {@link mergeMap}
* @see {@link mergeScan}
*
* @param {function(value: T, index: number) => Observable} project A function
* that, when applied to an item emitted by the source or the output Observable,
* returns an Observable.
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
* Observables being subscribed to concurrently.
* @param {SchedulerLike} [scheduler=null] The {@link SchedulerLike} to use for subscribing to
* each projected inner Observable.
* @return {Observable} An Observable that emits the source values and also
* result of applying the projection function to each value emitted on the
* output Observable and and merging the results of the Observables obtained
* from this transformation.
* @method expand
* @owner Observable
*/
export function expand<T, R>(project: (value: T, index: number) => ObservableInput<R>,
concurrent: number = Number.POSITIVE_INFINITY,
scheduler: SchedulerLike = undefined): OperatorFunction<T, R> {
concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
return (source: Observable<T>) => source.lift(new ExpandOperator(project, concurrent, scheduler));
}
export class ExpandOperator<T, R> implements Operator<T, R> {
constructor(private project: (value: T, index: number) => ObservableInput<R>,
private concurrent: number,
private scheduler: SchedulerLike) {
}
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
}
}
interface DispatchArg<T, R> {
subscriber: ExpandSubscriber<T, R>;
result: ObservableInput<R>;
value: any;
index: number;
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class ExpandSubscriber<T, R> extends OuterSubscriber<T, R> {
private index: number = 0;
private active: number = 0;
private hasCompleted: boolean = false;
private buffer: any[];
constructor(destination: Subscriber<R>,
private project: (value: T, index: number) => ObservableInput<R>,
private concurrent: number,
private scheduler: SchedulerLike) {
super(destination);
if (concurrent < Number.POSITIVE_INFINITY) {
this.buffer = [];
}
}
private static dispatch<T, R>(arg: DispatchArg<T, R>): void {
const {subscriber, result, value, index} = arg;
subscriber.subscribeToProjection(result, value, index);
}
protected _next(value: any): void {
const destination = this.destination;
if (destination.closed) {
this._complete();
return;
}
const index = this.index++;
if (this.active < this.concurrent) {
destination.next(value);
try {
const { project } = this;
const result = project(value, index);
if (!this.scheduler) {
this.subscribeToProjection(result, value, index);
} else {
const state: DispatchArg<T, R> = { subscriber: this, result, value, index };
const destination = this.destination as Subscription;
destination.add(this.scheduler.schedule<DispatchArg<T, R>>(ExpandSubscriber.dispatch, 0, state));
}
} catch (e) {
destination.error(e);
}
} else {
this.buffer.push(value);
}
}
private subscribeToProjection(result: any, value: T, index: number): void {
this.active++;
const destination = this.destination as Subscription;
destination.add(subscribeToResult<T, R>(this, result, value, index));
}
protected _complete(): void {
this.hasCompleted = true;
if (this.hasCompleted && this.active === 0) {
this.destination.complete();
}
this.unsubscribe();
}
notifyNext(outerValue: T, innerValue: R,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
this._next(innerValue);
}
notifyComplete(innerSub: Subscription): void {
const buffer = this.buffer;
const destination = this.destination as Subscription;
destination.remove(innerSub);
this.active--;
if (buffer && buffer.length > 0) {
this._next(buffer.shift());
}
if (this.hasCompleted && this.active === 0) {
this.destination.complete();
}
}
}

104
node_modules/rxjs/src/internal/operators/filter.ts generated vendored Normal file
View File

@ -0,0 +1,104 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OperatorFunction, MonoTypeOperatorFunction, TeardownLogic } from '../types';
/* tslint:disable:max-line-length */
export function filter<T, S extends T>(predicate: (value: T, index: number) => value is S,
thisArg?: any): OperatorFunction<T, S>;
export function filter<T>(predicate: (value: T, index: number) => boolean,
thisArg?: any): MonoTypeOperatorFunction<T>;
/* tslint:enable:max-line-length */
/**
* Filter items emitted by the source Observable by only emitting those that
* satisfy a specified predicate.
*
* <span class="informal">Like
* [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
* it only emits a value from the source if it passes a criterion function.</span>
*
* ![](filter.png)
*
* Similar to the well-known `Array.prototype.filter` method, this operator
* takes values from the source Observable, passes them through a `predicate`
* function and only emits those values that yielded `true`.
*
* ## Example
* Emit only click events whose target was a DIV element
* ```ts
* import { fromEvent } from 'rxjs';
* import { filter } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const clicksOnDivs = clicks.pipe(filter(ev => ev.target.tagName === 'DIV'));
* clicksOnDivs.subscribe(x => console.log(x));
* ```
*
* @see {@link distinct}
* @see {@link distinctUntilChanged}
* @see {@link distinctUntilKeyChanged}
* @see {@link ignoreElements}
* @see {@link partition}
* @see {@link skip}
*
* @param {function(value: T, index: number): boolean} predicate A function that
* evaluates each value emitted by the source Observable. If it returns `true`,
* the value is emitted, if `false` the value is not passed to the output
* Observable. The `index` parameter is the number `i` for the i-th source
* emission that has happened since the subscription, starting from the number
* `0`.
* @param {any} [thisArg] An optional argument to determine the value of `this`
* in the `predicate` function.
* @return {Observable} An Observable of values from the source that were
* allowed by the `predicate` function.
* @method filter
* @owner Observable
*/
export function filter<T>(predicate: (value: T, index: number) => boolean,
thisArg?: any): MonoTypeOperatorFunction<T> {
return function filterOperatorFunction(source: Observable<T>): Observable<T> {
return source.lift(new FilterOperator(predicate, thisArg));
};
}
class FilterOperator<T> implements Operator<T, T> {
constructor(private predicate: (value: T, index: number) => boolean,
private thisArg?: any) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class FilterSubscriber<T> extends Subscriber<T> {
count: number = 0;
constructor(destination: Subscriber<T>,
private predicate: (value: T, index: number) => boolean,
private thisArg: any) {
super(destination);
}
// the try catch block below is left specifically for
// optimization and perf reasons. a tryCatcher is not necessary here.
protected _next(value: T) {
let result: any;
try {
result = this.predicate.call(this.thisArg, value, this.count++);
} catch (err) {
this.destination.error(err);
return;
}
if (result) {
this.destination.next(value);
}
}
}

38
node_modules/rxjs/src/internal/operators/finalize.ts generated vendored Normal file
View File

@ -0,0 +1,38 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { Observable } from '../Observable';
import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
/**
* Returns an Observable that mirrors the source Observable, but will call a specified function when
* the source terminates on complete or error.
* @param {function} callback Function to be called when source terminates.
* @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
* @method finally
* @owner Observable
*/
export function finalize<T>(callback: () => void): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => source.lift(new FinallyOperator(callback));
}
class FinallyOperator<T> implements Operator<T, T> {
constructor(private callback: () => void) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new FinallySubscriber(subscriber, this.callback));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class FinallySubscriber<T> extends Subscriber<T> {
constructor(destination: Subscriber<T>, callback: () => void) {
super(destination);
this.add(new Subscription(callback));
}
}

109
node_modules/rxjs/src/internal/operators/find.ts generated vendored Normal file
View File

@ -0,0 +1,109 @@
import {Observable} from '../Observable';
import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {OperatorFunction} from '../types';
export function find<T, S extends T>(predicate: (value: T, index: number, source: Observable<T>) => value is S,
thisArg?: any): OperatorFunction<T, S | undefined>;
export function find<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,
thisArg?: any): OperatorFunction<T, T | undefined>;
/**
* Emits only the first value emitted by the source Observable that meets some
* condition.
*
* <span class="informal">Finds the first value that passes some test and emits
* that.</span>
*
* ![](find.png)
*
* `find` searches for the first item in the source Observable that matches the
* specified condition embodied by the `predicate`, and returns the first
* occurrence in the source. Unlike {@link first}, the `predicate` is required
* in `find`, and does not emit an error if a valid value is not found.
*
* ## Example
* Find and emit the first click that happens on a DIV element
* ```ts
* import { fromEvent } from 'rxjs';
* import { find } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(find(ev => ev.target.tagName === 'DIV'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link filter}
* @see {@link first}
* @see {@link findIndex}
* @see {@link take}
*
* @param {function(value: T, index: number, source: Observable<T>): boolean} predicate
* A function called with each item to test for condition matching.
* @param {any} [thisArg] An optional argument to determine the value of `this`
* in the `predicate` function.
* @return {Observable<T>} An Observable of the first item that matches the
* condition.
* @method find
* @owner Observable
*/
export function find<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,
thisArg?: any): OperatorFunction<T, T | undefined> {
if (typeof predicate !== 'function') {
throw new TypeError('predicate is not a function');
}
return (source: Observable<T>) => source.lift(new FindValueOperator(predicate, source, false, thisArg)) as Observable<T | undefined>;
}
export class FindValueOperator<T> implements Operator<T, T | number | undefined> {
constructor(private predicate: (value: T, index: number, source: Observable<T>) => boolean,
private source: Observable<T>,
private yieldIndex: boolean,
private thisArg?: any) {
}
call(observer: Subscriber<T>, source: any): any {
return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class FindValueSubscriber<T> extends Subscriber<T> {
private index: number = 0;
constructor(destination: Subscriber<T>,
private predicate: (value: T, index: number, source: Observable<T>) => boolean,
private source: Observable<T>,
private yieldIndex: boolean,
private thisArg?: any) {
super(destination);
}
private notifyComplete(value: any): void {
const destination = this.destination;
destination.next(value);
destination.complete();
this.unsubscribe();
}
protected _next(value: T): void {
const {predicate, thisArg} = this;
const index = this.index++;
try {
const result = predicate.call(thisArg || this, value, index, this.source);
if (result) {
this.notifyComplete(this.yieldIndex ? index : value);
}
} catch (err) {
this.destination.error(err);
}
}
protected _complete(): void {
this.notifyComplete(this.yieldIndex ? -1 : undefined);
}
}

47
node_modules/rxjs/src/internal/operators/findIndex.ts generated vendored Normal file
View File

@ -0,0 +1,47 @@
import { Observable } from '../Observable';
import { FindValueOperator } from '../operators/find';
import { OperatorFunction } from '../types';
/**
* Emits only the index of the first value emitted by the source Observable that
* meets some condition.
*
* <span class="informal">It's like {@link find}, but emits the index of the
* found value, not the value itself.</span>
*
* ![](findIndex.png)
*
* `findIndex` searches for the first item in the source Observable that matches
* the specified condition embodied by the `predicate`, and returns the
* (zero-based) index of the first occurrence in the source. Unlike
* {@link first}, the `predicate` is required in `findIndex`, and does not emit
* an error if a valid value is not found.
*
* ## Example
* Emit the index of first click that happens on a DIV element
* ```ts
* import { fromEvent } from 'rxjs';
* import { findIndex } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(findIndex(ev => ev.target.tagName === 'DIV'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link filter}
* @see {@link find}
* @see {@link first}
* @see {@link take}
*
* @param {function(value: T, index: number, source: Observable<T>): boolean} predicate
* A function called with each item to test for condition matching.
* @param {any} [thisArg] An optional argument to determine the value of `this`
* in the `predicate` function.
* @return {Observable} An Observable of the index of the first item that
* matches the condition.
* @method find
* @owner Observable
*/
export function findIndex<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean,
thisArg?: any): OperatorFunction<T, number> {
return (source: Observable<T>) => source.lift(new FindValueOperator(predicate, source, true, thisArg)) as Observable<any>;
}

91
node_modules/rxjs/src/internal/operators/first.ts generated vendored Normal file
View File

@ -0,0 +1,91 @@
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { EmptyError } from '../util/EmptyError';
import { OperatorFunction } from '../../internal/types';
import { filter } from './filter';
import { take } from './take';
import { defaultIfEmpty } from './defaultIfEmpty';
import { throwIfEmpty } from './throwIfEmpty';
import { identity } from '../util/identity';
/* tslint:disable:max-line-length */
export function first<T, D = T>(
predicate?: null,
defaultValue?: D
): OperatorFunction<T, T | D>;
export function first<T, S extends T>(
predicate: (value: T, index: number, source: Observable<T>) => value is S,
defaultValue?: S
): OperatorFunction<T, S>;
export function first<T, D = T>(
predicate: (value: T, index: number, source: Observable<T>) => boolean,
defaultValue?: D
): OperatorFunction<T, T | D>;
/* tslint:enable:max-line-length */
/**
* Emits only the first value (or the first value that meets some condition)
* emitted by the source Observable.
*
* <span class="informal">Emits only the first value. Or emits only the first
* value that passes some test.</span>
*
* ![](first.png)
*
* If called with no arguments, `first` emits the first value of the source
* Observable, then completes. If called with a `predicate` function, `first`
* emits the first value of the source that matches the specified condition. It
* may also take a deprecated `resultSelector` function to produce the output
* value from the input value, and a `defaultValue` to emit in case the source
* completes before it is able to emit a valid value. Throws an error if
* `defaultValue` was not provided and a matching element is not found.
*
* ## Examples
* Emit only the first click that happens on the DOM
* ```ts
* import { fromEvent } from 'rxjs';
* import { first } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(first());
* result.subscribe(x => console.log(x));
* ```
*
* Emits the first click that happens on a DIV
* ```ts
* import { fromEvent } from 'rxjs';
* import { first } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(first(ev => ev.target.tagName === 'DIV'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link filter}
* @see {@link find}
* @see {@link take}
*
* @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
* callback if the Observable completes before any `next` notification was sent.
*
* @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
* An optional function called with each item to test for condition matching.
* @param {R} [defaultValue] The default value emitted in case no valid value
* was found on the source.
* @return {Observable<T|R>} An Observable of the first item that matches the
* condition.
* @method first
* @owner Observable
*/
export function first<T, D>(
predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,
defaultValue?: D
): OperatorFunction<T, T | D> {
const hasDefaultValue = arguments.length >= 2;
return (source: Observable<T>) => source.pipe(
predicate ? filter((v, i) => predicate(v, i, source)) : identity,
take(1),
hasDefaultValue ? defaultIfEmpty<T | D>(defaultValue) : throwIfEmpty(() => new EmptyError()),
);
}

319
node_modules/rxjs/src/internal/operators/groupBy.ts generated vendored Normal file
View File

@ -0,0 +1,319 @@
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subject } from '../Subject';
import { OperatorFunction } from '../types';
/* tslint:disable:max-line-length */
export function groupBy<T, K>(keySelector: (value: T) => K): OperatorFunction<T, GroupedObservable<K, T>>;
export function groupBy<T, K>(keySelector: (value: T) => K, elementSelector: void, durationSelector: (grouped: GroupedObservable<K, T>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, T>>;
export function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, R>>;
export function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>, subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>>;
/* tslint:enable:max-line-length */
/**
* Groups the items emitted by an Observable according to a specified criterion,
* and emits these grouped items as `GroupedObservables`, one
* {@link GroupedObservable} per group.
*
* ![](groupBy.png)
*
* When the Observable emits an item, a key is computed for this item with the keySelector function.
*
* If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Elsewhere, a new
* {@link GroupedObservable} for this key is created and emits.
*
* A {@link GroupedObservable} represents values belonging to the same group represented by a common key. The common
* key is available as the key field of a {@link GroupedObservable} instance.
*
* The elements emitted by {@link GroupedObservable}s are by default the items emitted by the Observable, or elements
* returned by the elementSelector function.
*
* ## Examples
*
* ### Group objects by id and return as array
*
* ```ts
* import { of } from 'rxjs';
* import { mergeMap, groupBy, reduce } from 'rxjs/operators';
*
* of(
* {id: 1, name: 'JavaScript'},
* {id: 2, name: 'Parcel'},
* {id: 2, name: 'webpack'},
* {id: 1, name: 'TypeScript'},
* {id: 3, name: 'TSLint'}
* ).pipe(
* groupBy(p => p.id),
* mergeMap((group$) => group$.pipe(reduce((acc, cur) => [...acc, cur], []))),
* )
* .subscribe(p => console.log(p));
*
* // displays:
* // [ { id: 1, name: 'JavaScript'},
* // { id: 1, name: 'TypeScript'} ]
* //
* // [ { id: 2, name: 'Parcel'},
* // { id: 2, name: 'webpack'} ]
* //
* // [ { id: 3, name: 'TSLint'} ]
* ```
*
* ### Pivot data on the id field
*
* ```ts
* import { of } from 'rxjs';
* import { groupBy, map, mergeMap, reduce } from 'rxjs/operators';
*
* of(
* { id: 1, name: 'JavaScript' },
* { id: 2, name: 'Parcel' },
* { id: 2, name: 'webpack' },
* { id: 1, name: 'TypeScript' },
* { id: 3, name: 'TSLint' }
* )
* .pipe(
* groupBy(p => p.id, p => p.name),
* mergeMap(group$ =>
* group$.pipe(reduce((acc, cur) => [...acc, cur], [`${group$.key}`]))
* ),
* map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))
* )
* .subscribe(p => console.log(p));
*
* // displays:
* // { id: 1, values: [ 'JavaScript', 'TypeScript' ] }
* // { id: 2, values: [ 'Parcel', 'webpack' ] }
* // { id: 3, values: [ 'TSLint' ] }
* ```
*
* @param {function(value: T): K} keySelector A function that extracts the key
* for each item.
* @param {function(value: T): R} [elementSelector] A function that extracts the
* return element for each item.
* @param {function(grouped: GroupedObservable<K,R>): Observable<any>} [durationSelector]
* A function that returns an Observable to determine how long each group should
* exist.
* @return {Observable<GroupedObservable<K,R>>} An Observable that emits
* GroupedObservables, each of which corresponds to a unique key value and each
* of which emits those items from the source Observable that share that key
* value.
* @method groupBy
* @owner Observable
*/
export function groupBy<T, K, R>(keySelector: (value: T) => K,
elementSelector?: ((value: T) => R) | void,
durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,
subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>> {
return (source: Observable<T>) =>
source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
}
export interface RefCountSubscription {
count: number;
unsubscribe: () => void;
closed: boolean;
attemptedToUnsubscribe: boolean;
}
class GroupByOperator<T, K, R> implements Operator<T, GroupedObservable<K, R>> {
constructor(private keySelector: (value: T) => K,
private elementSelector?: ((value: T) => R) | void,
private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,
private subjectSelector?: () => Subject<R>) {
}
call(subscriber: Subscriber<GroupedObservable<K, R>>, source: any): any {
return source.subscribe(new GroupBySubscriber(
subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector
));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class GroupBySubscriber<T, K, R> extends Subscriber<T> implements RefCountSubscription {
private groups: Map<K, Subject<T | R>> = null;
public attemptedToUnsubscribe: boolean = false;
public count: number = 0;
constructor(destination: Subscriber<GroupedObservable<K, R>>,
private keySelector: (value: T) => K,
private elementSelector?: ((value: T) => R) | void,
private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,
private subjectSelector?: () => Subject<R>) {
super(destination);
}
protected _next(value: T): void {
let key: K;
try {
key = this.keySelector(value);
} catch (err) {
this.error(err);
return;
}
this._group(value, key);
}
private _group(value: T, key: K) {
let groups = this.groups;
if (!groups) {
groups = this.groups = new Map<K, Subject<T | R>>();
}
let group = groups.get(key);
let element: R;
if (this.elementSelector) {
try {
element = this.elementSelector(value);
} catch (err) {
this.error(err);
}
} else {
element = <any>value;
}
if (!group) {
group = (this.subjectSelector ? this.subjectSelector() : new Subject<R>()) as Subject<T | R>;
groups.set(key, group);
const groupedObservable = new GroupedObservable(key, group, this);
this.destination.next(groupedObservable);
if (this.durationSelector) {
let duration: any;
try {
duration = this.durationSelector(new GroupedObservable<K, R>(key, <Subject<R>>group));
} catch (err) {
this.error(err);
return;
}
this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));
}
}
if (!group.closed) {
group.next(element);
}
}
protected _error(err: any): void {
const groups = this.groups;
if (groups) {
groups.forEach((group, key) => {
group.error(err);
});
groups.clear();
}
this.destination.error(err);
}
protected _complete(): void {
const groups = this.groups;
if (groups) {
groups.forEach((group, key) => {
group.complete();
});
groups.clear();
}
this.destination.complete();
}
removeGroup(key: K): void {
this.groups.delete(key);
}
unsubscribe() {
if (!this.closed) {
this.attemptedToUnsubscribe = true;
if (this.count === 0) {
super.unsubscribe();
}
}
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class GroupDurationSubscriber<K, T> extends Subscriber<T> {
constructor(private key: K,
private group: Subject<T>,
private parent: GroupBySubscriber<any, K, T | any>) {
super(group);
}
protected _next(value: T): void {
this.complete();
}
/** @deprecated This is an internal implementation detail, do not use. */
_unsubscribe() {
const { parent, key } = this;
this.key = this.parent = null;
if (parent) {
parent.removeGroup(key);
}
}
}
/**
* An Observable representing values belonging to the same group represented by
* a common key. The values emitted by a GroupedObservable come from the source
* Observable. The common key is available as the field `key` on a
* GroupedObservable instance.
*
* @class GroupedObservable<K, T>
*/
export class GroupedObservable<K, T> extends Observable<T> {
/** @deprecated Do not construct this type. Internal use only */
constructor(public key: K,
private groupSubject: Subject<T>,
private refCountSubscription?: RefCountSubscription) {
super();
}
/** @deprecated This is an internal implementation detail, do not use. */
_subscribe(subscriber: Subscriber<T>) {
const subscription = new Subscription();
const { refCountSubscription, groupSubject } = this;
if (refCountSubscription && !refCountSubscription.closed) {
subscription.add(new InnerRefCountSubscription(refCountSubscription));
}
subscription.add(groupSubject.subscribe(subscriber));
return subscription;
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class InnerRefCountSubscription extends Subscription {
constructor(private parent: RefCountSubscription) {
super();
parent.count++;
}
unsubscribe() {
const parent = this.parent;
if (!parent.closed && !this.closed) {
super.unsubscribe();
parent.count -= 1;
if (parent.count === 0 && parent.attemptedToUnsubscribe) {
parent.unsubscribe();
}
}
}
}

View File

@ -0,0 +1,54 @@
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { OperatorFunction } from '../types';
/**
* Ignores all items emitted by the source Observable and only passes calls of `complete` or `error`.
*
* ![](ignoreElements.png)
*
* ## Examples
* ### Ignores emitted values, reacts to observable's completion.
* ```ts
* import { of } from 'rxjs';
* import { ignoreElements } from 'rxjs/operators';
*
* of('you', 'talking', 'to', 'me').pipe(
* ignoreElements(),
* )
* .subscribe(
* word => console.log(word),
* err => console.log('error:', err),
* () => console.log('the end'),
* );
* // result:
* // 'the end'
* ```
* @return {Observable} An empty Observable that only calls `complete`
* or `error`, based on which one is called by the source Observable.
* @method ignoreElements
* @owner Observable
*/
export function ignoreElements(): OperatorFunction<any, never> {
return function ignoreElementsOperatorFunction(source: Observable<any>) {
return source.lift(new IgnoreElementsOperator());
};
}
class IgnoreElementsOperator<T, R> implements Operator<T, R> {
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new IgnoreElementsSubscriber(subscriber));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class IgnoreElementsSubscriber<T> extends Subscriber<T> {
protected _next(unused: T): void {
// Do nothing
}
}

102
node_modules/rxjs/src/internal/operators/index.ts generated vendored Normal file
View File

@ -0,0 +1,102 @@
export { audit } from './audit';
export { auditTime } from './auditTime';
export { buffer } from './buffer';
export { bufferCount } from './bufferCount';
export { bufferTime } from './bufferTime';
export { bufferToggle } from './bufferToggle';
export { bufferWhen } from './bufferWhen';
export { catchError } from './catchError';
export { combineAll } from './combineAll';
export { combineLatest } from './combineLatest';
export { concat } from './concat';
export { concatAll } from './concatAll';
export { concatMap } from './concatMap';
export { concatMapTo } from './concatMapTo';
export { count } from './count';
export { debounce } from './debounce';
export { debounceTime } from './debounceTime';
export { defaultIfEmpty } from './defaultIfEmpty';
export { delay } from './delay';
export { delayWhen } from './delayWhen';
export { dematerialize } from './dematerialize';
export { distinct } from './distinct';
export { distinctUntilChanged } from './distinctUntilChanged';
export { distinctUntilKeyChanged } from './distinctUntilKeyChanged';
export { elementAt } from './elementAt';
export { every } from './every';
export { exhaust } from './exhaust';
export { exhaustMap } from './exhaustMap';
export { expand } from './expand';
export { filter } from './filter';
export { finalize } from './finalize';
export { find } from './find';
export { findIndex } from './findIndex';
export { first } from './first';
export { groupBy } from './groupBy';
export { ignoreElements } from './ignoreElements';
export { isEmpty } from './isEmpty';
export { last } from './last';
export { map } from './map';
export { mapTo } from './mapTo';
export { materialize } from './materialize';
export { max } from './max';
export { merge } from './merge';
export { mergeAll } from './mergeAll';
export { mergeMap } from './mergeMap';
export { mergeMap as flatMap } from './mergeMap';
export { mergeMapTo } from './mergeMapTo';
export { mergeScan } from './mergeScan';
export { min } from './min';
export { multicast } from './multicast';
export { observeOn } from './observeOn';
export { onErrorResumeNext } from './onErrorResumeNext';
export { pairwise } from './pairwise';
export { partition } from './partition';
export { pluck } from './pluck';
export { publish } from './publish';
export { publishBehavior } from './publishBehavior';
export { publishLast } from './publishLast';
export { publishReplay } from './publishReplay';
export { race } from './race';
export { reduce } from './reduce';
export { repeat } from './repeat';
export { repeatWhen } from './repeatWhen';
export { retry } from './retry';
export { retryWhen } from './retryWhen';
export { refCount } from './refCount';
export { sample } from './sample';
export { sampleTime } from './sampleTime';
export { scan } from './scan';
export { sequenceEqual } from './sequenceEqual';
export { share } from './share';
export { shareReplay } from './shareReplay';
export { single } from './single';
export { skip } from './skip';
export { skipLast } from './skipLast';
export { skipUntil } from './skipUntil';
export { skipWhile } from './skipWhile';
export { startWith } from './startWith';
export { subscribeOn } from './subscribeOn';
export { switchAll } from './switchAll';
export { switchMap } from './switchMap';
export { switchMapTo } from './switchMapTo';
export { take } from './take';
export { takeLast } from './takeLast';
export { takeUntil } from './takeUntil';
export { takeWhile } from './takeWhile';
export { tap } from './tap';
export { throttle } from './throttle';
export { throttleTime } from './throttleTime';
export { timeInterval } from './timeInterval';
export { timeout } from './timeout';
export { timeoutWith } from './timeoutWith';
export { timestamp } from './timestamp';
export { toArray } from './toArray';
export { window } from './window';
export { windowCount } from './windowCount';
export { windowTime } from './windowTime';
export { windowToggle } from './windowToggle';
export { windowWhen } from './windowWhen';
export { withLatestFrom } from './withLatestFrom';
export { zip } from './zip';
export { zipAll } from './zipAll';

100
node_modules/rxjs/src/internal/operators/isEmpty.ts generated vendored Normal file
View File

@ -0,0 +1,100 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OperatorFunction } from '../types';
/**
* Emits false if the input observable emits any values, or emits true if the
* input observable completes without emitting any values.
*
* <span class="informal">Tells whether any values are emitted by an observable</span>
*
* ![](isEmpty.png)
*
* `isEmpty` transforms an Observable that emits values into an Observable that
* emits a single boolean value representing whether or not any values were
* emitted by the source Observable. As soon as the source Observable emits a
* value, `isEmpty` will emit a `false` and complete. If the source Observable
* completes having not emitted anything, `isEmpty` will emit a `true` and
* complete.
*
* A similar effect could be achieved with {@link count}, but `isEmpty` can emit
* a `false` value sooner.
*
* ## Examples
*
* Emit `false` for a non-empty Observable
* ```javascript
* import { Subject } from 'rxjs';
* import { isEmpty } from 'rxjs/operators';
*
* const source = new Subject<string>();
* const result = source.pipe(isEmpty());
* source.subscribe(x => console.log(x));
* result.subscribe(x => console.log(x));
* source.next('a');
* source.next('b');
* source.next('c');
* source.complete();
*
* // Results in:
* // a
* // false
* // b
* // c
* ```
*
* Emit `true` for an empty Observable
* ```javascript
* import { EMPTY } from 'rxjs';
* import { isEmpty } from 'rxjs/operators';
*
* const result = EMPTY.pipe(isEmpty());
* result.subscribe(x => console.log(x));
* // Results in:
* // true
* ```
*
* @see {@link count}
* @see {@link EMPTY}
*
* @return {OperatorFunction<T, boolean>} An Observable of a boolean value indicating whether observable was empty or not
* @method isEmpty
* @owner Observable
*/
export function isEmpty<T>(): OperatorFunction<T, boolean> {
return (source: Observable<T>) => source.lift(new IsEmptyOperator());
}
class IsEmptyOperator implements Operator<any, boolean> {
call (observer: Subscriber<boolean>, source: any): any {
return source.subscribe(new IsEmptySubscriber(observer));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class IsEmptySubscriber extends Subscriber<any> {
constructor(destination: Subscriber<boolean>) {
super(destination);
}
private notifyComplete(isEmpty: boolean): void {
const destination = this.destination;
destination.next(isEmpty);
destination.complete();
}
protected _next(value: boolean) {
this.notifyComplete(false);
}
protected _complete() {
this.notifyComplete(true);
}
}

54
node_modules/rxjs/src/internal/operators/last.ts generated vendored Normal file
View File

@ -0,0 +1,54 @@
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { EmptyError } from '../util/EmptyError';
import { OperatorFunction } from '../../internal/types';
import { filter } from './filter';
import { takeLast } from './takeLast';
import { throwIfEmpty } from './throwIfEmpty';
import { defaultIfEmpty } from './defaultIfEmpty';
import { identity } from '../util/identity';
/* tslint:disable:max-line-length */
export function last<T, D = T>(
predicate?: null,
defaultValue?: D
): OperatorFunction<T, T | D>;
export function last<T, S extends T>(
predicate: (value: T, index: number, source: Observable<T>) => value is S,
defaultValue?: S
): OperatorFunction<T, S>;
export function last<T, D = T>(
predicate: (value: T, index: number, source: Observable<T>) => boolean,
defaultValue?: D
): OperatorFunction<T, T | D>;
/* tslint:enable:max-line-length */
/**
* Returns an Observable that emits only the last item emitted by the source Observable.
* It optionally takes a predicate function as a parameter, in which case, rather than emitting
* the last item from the source Observable, the resulting Observable will emit the last item
* from the source Observable that satisfies the predicate.
*
* ![](last.png)
*
* @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
* callback if the Observable completes before any `next` notification was sent.
* @param {function} [predicate] - The condition any source emitted item has to satisfy.
* @param {any} [defaultValue] - An optional default value to provide if last
* predicate isn't met or no values were emitted.
* @return {Observable} An Observable that emits only the last item satisfying the given condition
* from the source, or an NoSuchElementException if no such items are emitted.
* @throws - Throws if no items that match the predicate are emitted by the source Observable.
*/
export function last<T, D>(
predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,
defaultValue?: D
): OperatorFunction<T, T | D> {
const hasDefaultValue = arguments.length >= 2;
return (source: Observable<T>) => source.pipe(
predicate ? filter((v, i) => predicate(v, i, source)) : identity,
takeLast(1),
hasDefaultValue ? defaultIfEmpty<T | D>(defaultValue) : throwIfEmpty(() => new EmptyError()),
);
}

91
node_modules/rxjs/src/internal/operators/map.ts generated vendored Normal file
View File

@ -0,0 +1,91 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OperatorFunction } from '../types';
/**
* Applies a given `project` function to each value emitted by the source
* Observable, and emits the resulting values as an Observable.
*
* <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
* it passes each source value through a transformation function to get
* corresponding output values.</span>
*
* ![](map.png)
*
* Similar to the well known `Array.prototype.map` function, this operator
* applies a projection to each value and emits that projection in the output
* Observable.
*
* ## Example
* Map every click to the clientX position of that click
* ```ts
* import { fromEvent } from 'rxjs';
* import { map } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const positions = clicks.pipe(map(ev => ev.clientX));
* positions.subscribe(x => console.log(x));
* ```
*
* @see {@link mapTo}
* @see {@link pluck}
*
* @param {function(value: T, index: number): R} project The function to apply
* to each `value` emitted by the source Observable. The `index` parameter is
* the number `i` for the i-th emission that has happened since the
* subscription, starting from the number `0`.
* @param {any} [thisArg] An optional argument to define what `this` is in the
* `project` function.
* @return {Observable<R>} An Observable that emits the values from the source
* Observable transformed by the given `project` function.
* @method map
* @owner Observable
*/
export function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {
return function mapOperation(source: Observable<T>): Observable<R> {
if (typeof project !== 'function') {
throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
}
return source.lift(new MapOperator(project, thisArg));
};
}
export class MapOperator<T, R> implements Operator<T, R> {
constructor(private project: (value: T, index: number) => R, private thisArg: any) {
}
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class MapSubscriber<T, R> extends Subscriber<T> {
count: number = 0;
private thisArg: any;
constructor(destination: Subscriber<R>,
private project: (value: T, index: number) => R,
thisArg: any) {
super(destination);
this.thisArg = thisArg || this;
}
// NOTE: This looks unoptimized, but it's actually purposefully NOT
// using try/catch optimizations.
protected _next(value: T) {
let result: R;
try {
result = this.project.call(this.thisArg, value, this.count++);
} catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
}
}

72
node_modules/rxjs/src/internal/operators/mapTo.ts generated vendored Normal file
View File

@ -0,0 +1,72 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { OperatorFunction } from '../types';
/**
* Emits the given constant value on the output Observable every time the source
* Observable emits a value.
*
* <span class="informal">Like {@link map}, but it maps every source value to
* the same output value every time.</span>
*
* ![](mapTo.png)
*
* Takes a constant `value` as argument, and emits that whenever the source
* Observable emits a value. In other words, ignores the actual source value,
* and simply uses the emission moment to know when to emit the given `value`.
*
* ## Example
* Map every click to the string 'Hi'
* ```ts
* import { fromEvent } from 'rxjs';
* import { mapTo } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const greetings = clicks.pipe(mapTo('Hi'));
* greetings.subscribe(x => console.log(x));
* ```
*
* @see {@link map}
*
* @param {any} value The value to map each source value to.
* @return {Observable} An Observable that emits the given `value` every time
* the source Observable emits something.
* @method mapTo
* @owner Observable
*/
export function mapTo<T, R>(value: R): OperatorFunction<T, R> {
return (source: Observable<T>) => source.lift(new MapToOperator(value));
}
class MapToOperator<T, R> implements Operator<T, R> {
value: R;
constructor(value: R) {
this.value = value;
}
call(subscriber: Subscriber<R>, source: any): any {
return source.subscribe(new MapToSubscriber(subscriber, this.value));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class MapToSubscriber<T, R> extends Subscriber<T> {
value: R;
constructor(destination: Subscriber<R>, value: R) {
super(destination);
this.value = value;
}
protected _next(x: T) {
this.destination.next(this.value);
}
}

View File

@ -0,0 +1,94 @@
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Notification } from '../Notification';
import { OperatorFunction } from '../types';
/**
* Represents all of the notifications from the source Observable as `next`
* emissions marked with their original types within {@link Notification}
* objects.
*
* <span class="informal">Wraps `next`, `error` and `complete` emissions in
* {@link Notification} objects, emitted as `next` on the output Observable.
* </span>
*
* ![](materialize.png)
*
* `materialize` returns an Observable that emits a `next` notification for each
* `next`, `error`, or `complete` emission of the source Observable. When the
* source Observable emits `complete`, the output Observable will emit `next` as
* a Notification of type "complete", and then it will emit `complete` as well.
* When the source Observable emits `error`, the output will emit `next` as a
* Notification of type "error", and then `complete`.
*
* This operator is useful for producing metadata of the source Observable, to
* be consumed as `next` emissions. Use it in conjunction with
* {@link dematerialize}.
*
* ## Example
* Convert a faulty Observable to an Observable of Notifications
* ```ts
* import { of } from 'rxjs';
* import { materialize, map } from 'rxjs/operators';
*
* const letters = of('a', 'b', 13, 'd');
* const upperCase = letters.pipe(map(x => x.toUpperCase()));
* const materialized = upperCase.pipe(materialize());
* materialized.subscribe(x => console.log(x));
*
* // Results in the following:
* // - Notification {kind: "N", value: "A", error: undefined, hasValue: true}
* // - Notification {kind: "N", value: "B", error: undefined, hasValue: true}
* // - Notification {kind: "E", value: undefined, error: TypeError:
* // x.toUpperCase is not a function at MapSubscriber.letters.map.x
* // [as project] (http://1…, hasValue: false}
* ```
*
* @see {@link Notification}
* @see {@link dematerialize}
*
* @return {Observable<Notification<T>>} An Observable that emits
* {@link Notification} objects that wrap the original emissions from the source
* Observable with metadata.
* @method materialize
* @owner Observable
*/
export function materialize<T>(): OperatorFunction<T, Notification<T>> {
return function materializeOperatorFunction(source: Observable<T>) {
return source.lift(new MaterializeOperator());
};
}
class MaterializeOperator<T> implements Operator<T, Notification<T>> {
call(subscriber: Subscriber<Notification<T>>, source: any): any {
return source.subscribe(new MaterializeSubscriber(subscriber));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class MaterializeSubscriber<T> extends Subscriber<T> {
constructor(destination: Subscriber<Notification<T>>) {
super(destination);
}
protected _next(value: T) {
this.destination.next(Notification.createNext(value));
}
protected _error(err: any) {
const destination = this.destination;
destination.next(Notification.createError(err));
destination.complete();
}
protected _complete() {
const destination = this.destination;
destination.next(Notification.createComplete());
destination.complete();
}
}

55
node_modules/rxjs/src/internal/operators/max.ts generated vendored Normal file
View File

@ -0,0 +1,55 @@
import { reduce } from './reduce';
import { MonoTypeOperatorFunction } from '../types';
/**
* The Max operator operates on an Observable that emits numbers (or items that can be compared with a provided function),
* and when source Observable completes it emits a single item: the item with the largest value.
*
* ![](max.png)
*
* ## Examples
* Get the maximal value of a series of numbers
* ```ts
* import { of } from 'rxjs';
* import { max } from 'rxjs/operators';
*
* of(5, 4, 7, 2, 8).pipe(
* max(),
* )
* .subscribe(x => console.log(x)); // -> 8
* ```
*
* Use a comparer function to get the maximal item
* ```typescript
* import { of } from 'rxjs';
* import { max } from 'rxjs/operators';
*
* interface Person {
* age: number,
* name: string
* }
* of<Person>(
* {age: 7, name: 'Foo'},
* {age: 5, name: 'Bar'},
* {age: 9, name: 'Beer'},
* ).pipe(
* max<Person>((a: Person, b: Person) => a.age < b.age ? -1 : 1),
* )
* .subscribe((x: Person) => console.log(x.name)); // -> 'Beer'
* ```
*
* @see {@link min}
*
* @param {Function} [comparer] - Optional comparer function that it will use instead of its default to compare the
* value of two items.
* @return {Observable} An Observable that emits item with the largest value.
* @method max
* @owner Observable
*/
export function max<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {
const max: (x: T, y: T) => T = (typeof comparer === 'function')
? (x, y) => comparer(x, y) > 0 ? x : y
: (x, y) => x > y ? x : y;
return reduce(max);
}

41
node_modules/rxjs/src/internal/operators/merge.ts generated vendored Normal file
View File

@ -0,0 +1,41 @@
import { merge as mergeStatic } from '../observable/merge';
import { Observable } from '../Observable';
import { ObservableInput, OperatorFunction, MonoTypeOperatorFunction, SchedulerLike } from '../types';
/* tslint:disable:max-line-length */
/** @deprecated Deprecated in favor of static merge. */
export function merge<T>(scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T>(concurrent?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2>(v2: ObservableInput<T2>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2>(v2: ObservableInput<T2>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2, T3>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2, T3, T4>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2, T3, T4, T5>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, T2, T3, T4, T5, T6>(v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, concurrent?: number, scheduler?: SchedulerLike): OperatorFunction<T, T | T2 | T3 | T4 | T5 | T6>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T>(...observables: Array<ObservableInput<T> | SchedulerLike | number>): MonoTypeOperatorFunction<T>;
/** @deprecated Deprecated in favor of static merge. */
export function merge<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike | number>): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* @deprecated Deprecated in favor of static {@link merge}.
*/
export function merge<T, R>(...observables: Array<ObservableInput<any> | SchedulerLike | number>): OperatorFunction<T, R> {
return (source: Observable<T>) => source.lift.call(mergeStatic(source, ...observables));
}

66
node_modules/rxjs/src/internal/operators/mergeAll.ts generated vendored Normal file
View File

@ -0,0 +1,66 @@
import { mergeMap } from './mergeMap';
import { identity } from '../util/identity';
import { OperatorFunction, ObservableInput } from '../types';
/**
* Converts a higher-order Observable into a first-order Observable which
* concurrently delivers all values that are emitted on the inner Observables.
*
* <span class="informal">Flattens an Observable-of-Observables.</span>
*
* ![](mergeAll.png)
*
* `mergeAll` subscribes to an Observable that emits Observables, also known as
* a higher-order Observable. Each time it observes one of these emitted inner
* Observables, it subscribes to that and delivers all the values from the
* inner Observable on the output Observable. The output Observable only
* completes once all inner Observables have completed. Any error delivered by
* a inner Observable will be immediately emitted on the output Observable.
*
* ## Examples
* Spawn a new interval Observable for each click event, and blend their outputs as one Observable
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { map, mergeAll } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const higherOrder = clicks.pipe(map((ev) => interval(1000)));
* const firstOrder = higherOrder.pipe(mergeAll());
* firstOrder.subscribe(x => console.log(x));
* ```
*
* Count from 0 to 9 every second for each click, but only allow 2 concurrent timers
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { take, map, mergeAll } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const higherOrder = clicks.pipe(
* map((ev) => interval(1000).pipe(take(10))),
* );
* const firstOrder = higherOrder.pipe(mergeAll(2));
* firstOrder.subscribe(x => console.log(x));
* ```
*
* @see {@link combineAll}
* @see {@link concatAll}
* @see {@link exhaust}
* @see {@link merge}
* @see {@link mergeMap}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
* @see {@link switchAll}
* @see {@link switchMap}
* @see {@link zipAll}
*
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
* Observables being subscribed to concurrently.
* @return {Observable} An Observable that emits values coming from all the
* inner Observables emitted by the source Observable.
* @method mergeAll
* @owner Observable
*/
export function mergeAll<T>(concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction<ObservableInput<T>, T> {
return mergeMap(identity, concurrent);
}

181
node_modules/rxjs/src/internal/operators/mergeMap.ts generated vendored Normal file
View File

@ -0,0 +1,181 @@
import { Observable } from '../Observable';
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { subscribeToResult } from '../util/subscribeToResult';
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
import { map } from './map';
import { from } from '../observable/from';
/* tslint:disable:max-line-length */
export function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated resultSelector no longer supported, use inner map instead */
export function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated resultSelector no longer supported, use inner map instead */
export function mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link mergeAll}.</span>
*
* ![](mergeMap.png)
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an Observable, and then merging those resulting Observables and
* emitting the results of this merger.
*
* ## Example
* Map and flatten each letter to an Observable ticking every 1 second
* ```ts
* import { of, interval } from 'rxjs';
* import { mergeMap, map } from 'rxjs/operators';
*
* const letters = of('a', 'b', 'c');
* const result = letters.pipe(
* mergeMap(x => interval(1000).pipe(map(i => x+i))),
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // a0
* // b0
* // c0
* // a1
* // b1
* // c1
* // continues to list a,b,c with respective ascending integers
* ```
*
* @see {@link concatMap}
* @see {@link exhaustMap}
* @see {@link merge}
* @see {@link mergeAll}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
* @see {@link switchMap}
*
* @param {function(value: T, ?index: number): ObservableInput} project A function
* that, when applied to an item emitted by the source Observable, returns an
* Observable.
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
* Observables being subscribed to concurrently.
* @return {Observable} An Observable that emits the result of applying the
* projection function (and the optional deprecated `resultSelector`) to each item
* emitted by the source Observable and merging the results of the Observables
* obtained from this transformation.
* @method mergeMap
* @owner Observable
*/
export function mergeMap<T, R, O extends ObservableInput<any>>(
project: (value: T, index: number) => O,
resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,
concurrent: number = Number.POSITIVE_INFINITY
): OperatorFunction<T, ObservedValueOf<O>|R> {
if (typeof resultSelector === 'function') {
// DEPRECATED PATH
return (source: Observable<T>) => source.pipe(
mergeMap((a, i) => from(project(a, i)).pipe(
map((b: any, ii: number) => resultSelector(a, b, i, ii)),
), concurrent)
);
} else if (typeof resultSelector === 'number') {
concurrent = resultSelector;
}
return (source: Observable<T>) => source.lift(new MergeMapOperator(project, concurrent));
}
export class MergeMapOperator<T, R> implements Operator<T, R> {
constructor(private project: (value: T, index: number) => ObservableInput<R>,
private concurrent: number = Number.POSITIVE_INFINITY) {
}
call(observer: Subscriber<R>, source: any): any {
return source.subscribe(new MergeMapSubscriber(
observer, this.project, this.concurrent
));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class MergeMapSubscriber<T, R> extends OuterSubscriber<T, R> {
private hasCompleted: boolean = false;
private buffer: T[] = [];
private active: number = 0;
protected index: number = 0;
constructor(destination: Subscriber<R>,
private project: (value: T, index: number) => ObservableInput<R>,
private concurrent: number = Number.POSITIVE_INFINITY) {
super(destination);
}
protected _next(value: T): void {
if (this.active < this.concurrent) {
this._tryNext(value);
} else {
this.buffer.push(value);
}
}
protected _tryNext(value: T) {
let result: ObservableInput<R>;
const index = this.index++;
try {
result = this.project(value, index);
} catch (err) {
this.destination.error(err);
return;
}
this.active++;
this._innerSub(result, value, index);
}
private _innerSub(ish: ObservableInput<R>, value: T, index: number): void {
const innerSubscriber = new InnerSubscriber(this, value, index);
const destination = this.destination as Subscription;
destination.add(innerSubscriber);
const innerSubscription = subscribeToResult<T, R>(this, ish, undefined, undefined, innerSubscriber);
// The returned subscription will usually be the subscriber that was
// passed. However, interop subscribers will be wrapped and for
// unsubscriptions to chain correctly, the wrapper needs to be added, too.
if (innerSubscription !== innerSubscriber) {
destination.add(innerSubscription);
}
}
protected _complete(): void {
this.hasCompleted = true;
if (this.active === 0 && this.buffer.length === 0) {
this.destination.complete();
}
this.unsubscribe();
}
notifyNext(outerValue: T, innerValue: R,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
this.destination.next(innerValue);
}
notifyComplete(innerSub: Subscription): void {
const buffer = this.buffer;
this.remove(innerSub);
this.active--;
if (buffer.length > 0) {
this._next(buffer.shift());
} else if (this.active === 0 && this.hasCompleted) {
this.destination.complete();
}
}
}

Some files were not shown because too many files have changed in this diff Show More