Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. import Rx from "rxjs";
  2.  
  3. class Throttler {
  4. /**
  5. * A Subject behaves as an event stream. You pump values
  6. * into the stream and each value gets pumped through
  7. * the pipeline below.
  8. */
  9. request$ = new Rx.Subject();
  10.  
  11. constructor() {
  12. this.request$
  13. /* Scan keeps track of what request number we're on. */
  14. .scan((acc, url, index) => {
  15. const delay = (index < 5)
  16. ? (index === 0) ? 0 : 1
  17. : 1000;
  18.  
  19. return {
  20. url: url,
  21. delay: delay
  22. };
  23. }, {})
  24. .flatMap(({ url, delay }) => {
  25. /* Timer will delay by the given `delay`
  26. and then make the request. */
  27. return Rx.Observable.timer(delay)
  28. .flatMap(() =>
  29. Rx.Observable.fromPromise(
  30. // axios.get(url, { responseType: 'json' })
  31. new Promise( ( resolve, reject ) => {
  32. setTimeout(function () { resolve({data: url}); }, 3000)
  33. } )
  34.  
  35. )
  36. );
  37. })
  38. /* subscribe() receives responses as they stream through. */
  39. .subscribe((data) => {
  40. console.log(data);
  41. });
  42. }
  43.  
  44. makeRequest(url) {
  45. this.request$.next(url); // Pumps the URL into the stream.
  46. }
  47. }
  48.  
  49. export default Throttler;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement