|
| 1 | +import { Operator } from '../Operator'; |
| 2 | +import { Subscriber } from '../Subscriber'; |
| 3 | +import { Observable } from '../Observable'; |
| 4 | +import { EmptyObservable } from '../observable/EmptyObservable'; |
| 5 | +import { TeardownLogic } from '../Subscription'; |
| 6 | +import { MonoTypeOperatorFunction } from '../interfaces'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Returns an Observable that repeats the stream of items emitted by the source Observable at most count times. |
| 10 | + * |
| 11 | + * <img src="./img/repeat.png" width="100%"> |
| 12 | + * |
| 13 | + * @param {number} [count] The number of times the source Observable items are repeated, a count of 0 will yield |
| 14 | + * an empty Observable. |
| 15 | + * @return {Observable} An Observable that repeats the stream of items emitted by the source Observable at most |
| 16 | + * count times. |
| 17 | + * @method repeat |
| 18 | + * @owner Observable |
| 19 | + */ |
| 20 | +export function repeat<T>(count: number = -1): MonoTypeOperatorFunction<T> { |
| 21 | + return (source: Observable<T>) => { |
| 22 | + if (count === 0) { |
| 23 | + return new EmptyObservable<T>(); |
| 24 | + } else if (count < 0) { |
| 25 | + return source.lift(new RepeatOperator(-1, source)); |
| 26 | + } else { |
| 27 | + return source.lift(new RepeatOperator(count - 1, source)); |
| 28 | + } |
| 29 | + }; |
| 30 | +} |
| 31 | + |
| 32 | +class RepeatOperator<T> implements Operator<T, T> { |
| 33 | + constructor(private count: number, |
| 34 | + private source: Observable<T>) { |
| 35 | + } |
| 36 | + call(subscriber: Subscriber<T>, source: any): TeardownLogic { |
| 37 | + return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source)); |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * We need this JSDoc comment for affecting ESDoc. |
| 43 | + * @ignore |
| 44 | + * @extends {Ignored} |
| 45 | + */ |
| 46 | +class RepeatSubscriber<T> extends Subscriber<T> { |
| 47 | + constructor(destination: Subscriber<any>, |
| 48 | + private count: number, |
| 49 | + private source: Observable<T>) { |
| 50 | + super(destination); |
| 51 | + } |
| 52 | + complete() { |
| 53 | + if (!this.isStopped) { |
| 54 | + const { source, count } = this; |
| 55 | + if (count === 0) { |
| 56 | + return super.complete(); |
| 57 | + } else if (count > -1) { |
| 58 | + this.count = count - 1; |
| 59 | + } |
| 60 | + source.subscribe(this._unsubscribeAndRecycle()); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments