【问题标题】:RXJS missing throttleWhile operator?RXJS 缺少throttleWhile 运算符?
【发布时间】:2019-09-22 15:13:50
【问题描述】:

令人惊讶的是,Rxjs 中似乎没有 throttleWhile 运算符。

我的用例很简单:

HTTP 事件,在文件上传过程中发出。

如果事件是HttpEventType.UploadProgress 类型,我想限制它们,如果是HttpEventType.Response,我想限制它们(捕获最终值,即响应)

我的服务电话:

this.httpService
  .uploadDocument(file)
  .pipe(
    throttleTime(200) // <-- would luv throttleWhile here
  )
  .subscribe((ev: HttpEvent<any>) => {
    if (ev.type === HttpEventType.UploadProgress) {
      const percentDone = Math.round(100 * ev.loaded / ev.total);
      console.log(percentDone);
      this.progress = percentDone;
    } else if (ev.type === HttpEventType.Response) {
      console.log(ev);
    }
  })

有什么想法吗?

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    我建议你使用下一个解决方案:

    import {throttleTime, partition, take}  from 'rxjs/operators';
    import  {timer} from 'rxjs';
    
    let a$ = timer(0, 120).pipe(take(10));
    let hasRequiredType = v => v === 9;
    let [done$, load$] = partition(hasRequiredType)(a$);
    load$.pipe(throttleTime(300)).subscribe(v => console.log("loading", v));
    done$.subscribe(v => console.log("done", v));
    

    https://stackblitz.com/edit/typescript-hzu3sp

    【讨论】:

    • 从库中导入所有内容时,这不是一个好方法,因为它会影响包大小
    • 是的,我这样做只是为了举例
    【解决方案2】:

    只有throttlethrottletime

    所以考虑一下你的需要,我认为你可以选择throttleTime

    // RxJS v6+
    import { interval } from 'rxjs';
    import { throttleTime } from 'rxjs/operators';
    
    //emit value every 1 second
    const source = interval(1000);
    /*
      throttle for five seconds
      last value emitted before throttle ends will be emitted from source
    */
    const example = source.pipe(throttleTime(5000));
    //output: 0...6...12
    const subscribe = example.subscribe(val => console.log(val));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 2015-05-18
      • 2016-12-04
      • 2021-12-26
      • 1970-01-01
      • 2021-01-16
      • 2017-04-28
      相关资源
      最近更新 更多