角间隔管道,内部任务更长 [英] Angular interval pipe with a longer task inside

查看:68
本文介绍了角间隔管道,内部任务更长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件中包含以下代码:

I have this code inside my component:

  ngOnInit() {
    ...
    this.counterValue$ = interval(1000).pipe(
      switchMap(() => this.perfService.getCounter(this.counterUrl)),
      map(i => this.updateChart(i)),
    );
    this.counterValue$.subscribe(v => console.log(v));
  }

我写这是为了每1秒更新一次图表.问题是perfService.getCounter()花费了1秒以上的时间才能返回.这将导致以下http请求被取消:

I wrote this to update a chart every 1s. The problem is that the perfService.getCounter() is taking more than 1s to return. And this causes the following http requests to get canceled:

该如何解决?

推荐答案

如果您希望每1秒更新一次,而大多数请求花费的时间超过1s,那么适合您的运算符可能是exhaustMap.

If you want to update it every 1s while most of the request are taking more than 1s the right operator for you is probably exhaustMap.

简短摘要在这种情况下,其他*map运算符之间有何区别:

Short summary what are the differences between other *map operators in this case:

  • switchMap将针对interval(1000)的每次发射取消待处理的请求.

  • switchMap will cancel the pending request on every emission from interval(1000).

mergeMap将针对interval(1000)的每个发射发出新请求,因此您将同时有许多待处理的请求,然后在它们到达时覆盖它们的响应

mergeMap will make a new request for every emission from interval(1000) so you'll have many pending request at the same time and then overriding their responses as they arrive

concatMap将堆叠来自interval(1000)的传入排放,然后在完成时执行它们,因此,如果您的响应时间很慢,然后响应非常快,那么concatMap就会发出更多请求然后在1s之后,因为它将首先为空,这是内部缓冲区.

concatMap will stack the incoming emissions from interval(1000) and then execute them as they complete so if you have a period of very slow responses and then then very fast responses concatMap will be making requests more often then after 1s because it'll first empty it's inner buffer.

exhaustMap将发出一个请求,然后忽略interval(1000)的任何后续发出,直到其内部请求完成.不管需要多长时间.然后它将等待来自Observable源的另一次发射.因此,您可以确保至少有1秒的延迟,而不会产生重叠的请求.

exhaustMap will make a request and then ignore any subsequent emission from interval(1000) until its inner request completes. No matter how long it takes. Then it'll wait for another emission from the source Observable. So you're guaranteed to have at least 1s delays while not spawning overlapping requests.

这篇关于角间隔管道,内部任务更长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆