zoukankan      html  css  js  c++  java
  • [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)
        }
      }
    }

  • 相关阅读:
    Alpha冲刺博客集
    Alpha冲刺——第一天
    团队项目需求分析
    结对第二次作业
    项目选题报告
    随笔2 PAT1001.A+B Format (20)
    随笔1 大一下学期自我目标
    大数
    列变位法解密--百度之星B题
    hdu1874 畅通工程续 dijkstra 最短路
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9721703.html
Copyright © 2011-2022 走看看