每天实现一个Rxjs中的Operator之combineLatest操作(二)

上一篇中介绍了combineLatest的使用,下面我们列出其核心代码实现:

class CombineLatestSubscriber extends OuterSubscriber {
  _next(observable) {
    this.values.push(none);
    this.observables.push(observable);
  }

  _complete() {
    const observables = this.observables;
    const len = observables.length;
    if (len === 0) {
      this.destination.complete();
    } else {
      this.toRespond = len;
      for (let i = 0; i < len; i++) {
        const observable = observables[i];
        subscribeToResult(this, observable, observable, i);
      }
    }
  }

  notifyNext(outerValue, innerValue, outerIndex) {
    const values = this.values;
    const oldVal = values[outerIndex];
    const toRespond = !this.toRespond
      ? 0
      : oldVal === none ? --this.toRespond : this.toRespond;
    values[outerIndex] = innerValue;
    if (toRespond === 0) {
      this.destination.next(values);
    }
  }

}

export class CombineLatestOperator {
  call(subscriber, source) {
    return source.subscribe(new CombineLatestSubscriber(subscriber));
  }
}

export function higherOrderCombineLatest(observables) {
  return source => source.lift.call(new ArrayObservable([source, ...observables]), new CombineLatestOperator());

代码中可以看出:

  1. CombineLatest操作调用时,会将参数Observable和source Observable创建一个新的Observable,而且该Observable是一个数组。
  2. ArrayObservable的subscribe方法执行时,会将所有的observable存储在CombineLatestSubscriber的observables变量中
  3. 执行ArrayObservable的方法_complete,会调用CombineLatestSubscriber的_complete方法,在该方法中会在每个observable emit数据的时候调用notifyNext方法。
  4. notifyNext中我们可以看到,values数组中存储的是每个observable发射的最新数据,而且只有所有observable都发射过数据,也就是toRespond为0的时候才会执行destination的next方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值