|
| 1 | +import Operator from '../Operator'; |
| 2 | +import Observer from '../Observer'; |
| 3 | +import Subscriber from '../Subscriber'; |
| 4 | +import Observable from '../Observable'; |
| 5 | + |
| 6 | +import tryCatch from '../util/tryCatch'; |
| 7 | +import {errorObject} from '../util/errorObject'; |
| 8 | + |
| 9 | +export default function withLatestFrom<R>(...args: (Observable<any>|((...values: any[]) => Observable<R>))[]): Observable<R> { |
| 10 | + const project = <((...values: any[]) => Observable<R>)>args.pop(); |
| 11 | + const observables = <Observable<any>[]>args; |
| 12 | + return this.lift(new WithLatestFromOperator(observables, project)); |
| 13 | +} |
| 14 | + |
| 15 | +export class WithLatestFromOperator<T, R> implements Operator<T, R> { |
| 16 | + constructor(private observables: Observable<any>[], private project: (...values: any[]) => Observable<R>) { |
| 17 | + } |
| 18 | + |
| 19 | + call(observer: Observer<R>): Observer<T> { |
| 20 | + return new WithLatestFromSubscriber<T, R>(observer, this.observables, this.project); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +export class WithLatestFromSubscriber<T, R> extends Subscriber<T> { |
| 25 | + private values: any[]; |
| 26 | + private toSet: number; |
| 27 | + |
| 28 | + constructor(destination: Observer<T>, private observables: Observable<any>[], private project: (...values: any[]) => Observable<R>) { |
| 29 | + super(destination); |
| 30 | + const len = observables.length; |
| 31 | + this.values = new Array(len); |
| 32 | + this.toSet = len; |
| 33 | + for (let i = 0; i < len; i++) { |
| 34 | + this.add(observables[i].subscribe(new WithLatestInnerSubscriber(this, i))) |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + notifyValue(index, value) { |
| 39 | + this.values[index] = value; |
| 40 | + this.toSet--; |
| 41 | + } |
| 42 | + |
| 43 | + _next(value: T) { |
| 44 | + if (this.toSet === 0) { |
| 45 | + const values = this.values; |
| 46 | + let result = tryCatch(this.project)([value, ...values]); |
| 47 | + if (result === errorObject) { |
| 48 | + this.destination.error(result.e); |
| 49 | + } else { |
| 50 | + this.destination.next(result); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +export class WithLatestInnerSubscriber<T, R> extends Subscriber<T> { |
| 57 | + constructor(private parent: WithLatestFromSubscriber<T, R>, private valueIndex: number) { |
| 58 | + super(null) |
| 59 | + } |
| 60 | + |
| 61 | + _next(value: T) { |
| 62 | + this.parent.notifyValue(this.valueIndex, value); |
| 63 | + } |
| 64 | + |
| 65 | + _error(err: any) { |
| 66 | + this.parent.error(err); |
| 67 | + } |
| 68 | + |
| 69 | + _complete() { |
| 70 | + // noop |
| 71 | + } |
| 72 | +} |
0 commit comments