内部有较长任务的角间隔管

内部有较长任务的角间隔管

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

问题描述

我的组件中有此代码:

  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 秒更新一次,而大多数请求都需要 1 秒以上,那么适合您的操作符可能是 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 会比 1 秒后更频繁地发出请求,因为它会首先清空它的内部缓冲区.

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.

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

09-02 04:22