Stavm
Stavm

Reputation: 8131

RXJS missing throttleWhile operator?

Surprisingly there seem to be no throttleWhile operator in Rxjs.

My use case is simple:

HTTP events, emitted off a file uploading process.

I would like to throttle them, if the event is of type HttpEventType.UploadProgress and don't, if it's HttpEventType.Response (to catch the final value, which is, a response)

My service call:

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

Any ideas ?

Upvotes: 0

Views: 106

Answers (2)

Tony
Tony

Reputation: 20122

There are only throttle and throttletime

So consider your need I think you can go for 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));

Upvotes: 0

dsych
dsych

Reputation: 762

I suggest you to go with the next solution:

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

Upvotes: 2

Related Questions