javascript - 了解 rxjs 中的 SwitchMap

标签 javascript rxjs reactive-programming rxjs6 switchmap

根据switchMap的定义

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.

现在,我有这样的代码

const source = timer(0, 5000).pipe(map(x=>`${x}`));
const example = source.pipe(switchMap((f) => interval(1000).pipe(map(y=>`f${f}-s${y}`))),take(20));
const subscribe = example.subscribe(val => console.log(val+' '+ new Date().getSeconds()));

结果是这样的

enter image description here

我的问题是,

  1. 第 25 秒 - 外部函数被调用,内部函数尚未被触发,因此外部函数的最新值为 0,内部函数也默认为 0,因为它还没有值 < strong>f0-s0 25

  2. 第 26 秒 - 内部函数被调用,理想情况下该值应该为 0,因为该函数只是第一次被调用,但它是 1,即。 f0-s1 26

  3. 第 30 秒 - 调用外部函数,将内部函数值重置为 0,即。 f1-s0 30

  4. 为什么第35秒内函数重置了,还剩1秒

stackblitz link

我觉得这个概念很难理解,谢谢

最佳答案

这是因为默认情况下,RxJS 的异步操作使用 setTimeoutsetInterval 函数,它们不能保证它们会准确地达到您想要的超时。

因此,如果您使用超时 50001000,则无法保证 5 秒后哪个操作会先发生。有时外层 Observable 先发出,有时内层先发出,但 switchMap 对此无能为力。

您可以看到时间有多么不同,例如。这个:

const start = new Date().getTime();
setInterval(() => console.log(new Date().getTime() - start), 1000);

现场演示:https://stackblitz.com/edit/typescript-urep5j

1004
2001
3002
4000
4998
...

所以有时延迟是 1004 而其他时候只是 998

关于javascript - 了解 rxjs 中的 SwitchMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55530961/

相关文章:

javascript - window.sidebar.addPanel 不再在 Firefox 上运行

javascript - 如何在 Angular http 拦截器中以异步方式缓存 http 请求?

firebase - 将 rxjs Observable 与 firestore 一起使用

c++ - RXcpp 连续从函数流式传输数据

r - 带有 Observes 和 reactiveValues 的 Shiny 模块

javascript - 在 "Fixed"容器 Div 中垂直放置一个 Div "Absolute",水平放置一个 "Position:Relative"

javascript - 增加 ReCaptcha 过期时间?

javascript - 获取 HTML 输入中的插入符号位置?

RxJS:是否有一个运算符像 mergeScan 一样工作,但只是在外部流发出时取消订阅内部流

java - 从过滤后的 Observable 返回最终列表