[RxJS] Implement RxJS `concatMap` by Waiting for Inner Subscriptions to Complete

Unlike mergeMap and switchMapconcatMap focuses on when "inner" subscriptions "complete" by using a "buffer". Each time concatMap receives a value, it adds each value to a "buffer", waits for previous "inner" subscription to complete, then invokes next with the next value from the "buffer".

class MyConcatMapSubscriber extends Subscriber {
  innerSubscription;

  buffer = [];

  constructor(sub, fn) {
    super(sub);

    this.fn = fn;
  }

  _next(value) {
    const { isStopped } = this.innerSubscription || {
      isStopped: true
    };

    if (!isStopped) {
      this.buffer = [...this.buffer, value];
    } else {
      const o$ = this.fn(value);
      this.innerSubscription = o$.subscribe({
        next: value => {
          this.destination.next(value);
        },
        complete: () => {
          if (this.buffer.length) {
            const { first, ...rest } = this.buffer;
            this.buffer = rest;
            this._next(first);
          }
        }
      });
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/9721702.html