rxjs switchMap的实现原理

时间:2022-07-25
本文章向大家介绍rxjs switchMap的实现原理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

SwitchMap can cancel in-flight network requests.

先引用rxjs官网对SwitchMap的介绍:

The main difference between switchMap and other flattening operators is the cancelling effect. On each emission the previous inner observable (the result of the function you supplied) is cancelled and the new observable is subscribed. You can remember this by the phrase switch to a new observable.

This works perfectly for scenarios like typeaheads where you are no longer concerned with the response of the previous request when a new input arrives. This also is a safe option in situations where a long lived inner observable could cause memory leaks, for instance if you used mergeMap with an interval and forgot to properly dispose of inner subscriptions. Remember, switchMap maintains only one inner subscription at a time, this can be seen clearly in the first example. Be careful though, you probably want to avoid switchMap in scenarios where every request needs to complete, think writes to a database. switchMap could cancel a request if the source emits quickly enough. In these scenarios mergeMap is the correct option.

看个例子:

源代码:

  ngOnInit(): void {
    fromEvent(document, 'click')
  .pipe(
    // restart counter on every click
    switchMap(() => interval(1000))
  )
  .subscribe((oe) => console.log('Jerry: ' + oe));
  }

输出:

switchMap的实现:

应用程序调用subscribe:

每次调用intervals函数,内部都会新建一个Observable对象:

调用了当前的next方法后,计数器加一,然后继续在preriod毫秒后,调度下一次执行:

返回一个新的Observable对象: