repeat.js 1.8 KB

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