Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Rx from "rxjs";
- class Throttler {
- /**
- * A Subject behaves as an event stream. You pump values
- * into the stream and each value gets pumped through
- * the pipeline below.
- */
- request$ = new Rx.Subject();
- constructor() {
- this.request$
- /* Scan keeps track of what request number we're on. */
- .scan((acc, url, index) => {
- const delay = (index < 5)
- ? (index === 0) ? 0 : 1
- : 1000;
- return {
- url: url,
- delay: delay
- };
- }, {})
- .flatMap(({ url, delay }) => {
- /* Timer will delay by the given `delay`
- and then make the request. */
- return Rx.Observable.timer(delay)
- .flatMap(() =>
- Rx.Observable.fromPromise(
- // axios.get(url, { responseType: 'json' })
- new Promise( ( resolve, reject ) => {
- setTimeout(function () { resolve({data: url}); }, 3000)
- } )
- )
- );
- })
- /* subscribe() receives responses as they stream through. */
- .subscribe((data) => {
- console.log(data);
- });
- }
- makeRequest(url) {
- this.request$.next(url); // Pumps the URL into the stream.
- }
- }
- export default Throttler;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement