RXJS缺少节气门

时间:2019-09-22 15:13:50

标签: javascript angular typescript rxjs

令人惊讶的是,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);
    }
  })

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

我建议您采用下一个解决方案:

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

答案 1 :(得分:0)

只有throttlethrottletime

因此,考虑到您的需求,我认为您可以节省油门时间

// 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));