[RxJS] `add` Inner Subscriptions to Outer Subscribers to `unsubscribe` in RxJS

When subscribers create new "inner" sources and subscriptions, you run the risk of losing control of them when the outer subscriber unsubscribes. This is handled easily enough if you use the add method from the Subscriber class to add the "inner" subscription to the Subscriber.

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: () => {
          console.log(this.buffer)
          if (this.buffer.length) {
            const [first, ...rest] = this.buffer
            this.buffer = rest
            this._next(first)
          }
        }
      })

      // to tell when the outter subscription complete, the inner subscription should also completed
      this.add(this.innerSubscription)
    }
  }
}

猜你喜欢

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