前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >rxjs switchMap的实现原理

rxjs switchMap的实现原理

作者头像
Jerry Wang
发布2020-09-27 14:34:16
8650
发布2020-09-27 14:34:16
举报

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.

看个例子:

源代码:

代码语言:javascript
复制
  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对象:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档