【问题标题】:RxJS: Make a single API request from a function which might have been called multiple timesRxJS:从可能被多次调用的函数发出单个 API 请求
【发布时间】:2020-03-31 17:58:49
【问题描述】:

组件控制器:

private updateSplitScreenService = () => {
    this.splitScreenService.emitNewState(this.products);
    this.splitScreenService.emitNewState(this.stores);
};

splitScreenService:


// emitNewState is called multiple times in quick succession but
// we want to only fire one API request and return the observable back 
// to the component
public emitNewState = (items: Products[] | Stores[]): void => {
    // If we already have a debounce active but a new call to emit 
    // the state has come in, cancel the current one.
    if (this.debounceTimeout) {
        clearTimeout(this.debounceTimeout);
    }

    // Create a new timeout
    this.debounceTimeout = setTimeout(() => {
        this.http.post().subscribe();
    }, 500);
};

正如您在上面看到的,我正在从我的组件调用一个具有自定义“去抖动”功能的服务函数,以确保只有在上次调用后 500 毫秒内没有再次调用该函数时才会发生 API 请求。 500ms内的任何调用都会取消之前设置的debounce函数发起API请求,再次设置超时函数等待调用API请求。这可确保 API 仅被调用一次。

但是,如果我想将 API 请求的 observable 返回到我的组件控制器,我会遇到如何从自定义去抖动/超时函数本身返回它的问题。目标是消除呼叫抖动,以便订阅者不仅只收到 1 个结果,而且之前的呼叫也被取消(或根本不进行)。

【问题讨论】:

  • 能否请您更新示例,以便可以运行和使用它。这将有助于更轻松地理解您的问题
  • 为了补充 Shlang 的建议,我们需要对问题本身的代码进行合理的表示。 Stack Overflow 中有一个代码编辑器,允许代码在 原位 运行,但如果这不起作用,您可以在问题中显示静态代码,然后在最后链接到 Plnkr。谢谢!
  • 感谢您的反馈,我删除了 plnkr 链接并将相关代码移动到问题本身。

标签: angular rxjs rxjs-observables


【解决方案1】:

尝试利用Rxjs 内置的debounceTime

import { debounceTime, switchMap } from 'rxjs';
...
emitNewState$ = new Subject();
...

ngOnInit() {
  this.listenToEmitNewState$();
}
....
emitNewState() {
  this.emitNewState$.next();
}

listenToEmitNewState$() {
  this.emitNewState$.pipe(
    debounceTime(500),
  ).subscribe(() => {
    // do what you want, but if you're going to do an HTTP call, use switchMap like how it is commented below
  });

  //this.emitNewState$.pipe(
    // debounceTime(500),
     //switchMap(() => this.http.post()),
  // ).subscribe(() => {....});
}

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 2016-06-10
    • 2017-03-21
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    相关资源
    最近更新 更多