Dan Rasmuson
Dan Rasmuson

Reputation: 6023

RxJS: Send x requests per second

I have function createEvent() which sends a request to google calendar.

Google Calendar's API requires me to send at max 5 requests per second.

If I call createEvent() 100 times it will flood google calendar and my requests are denied. If possible I would like createEvent() to contain the logic required to throttle requests to 5 per second.

I'm trying to avoid,

calendar.addEventToQueue(eventData);
calendar.addEventToQueue(eventData);
calendar.addEventToQueue(eventData);
cleandar.submitEvents();

and instead just

calendar.createEvent(eventData);
calendar.createEvent(eventData);
calendar.createEvent(eventData);

Upvotes: 1

Views: 884

Answers (1)

paulpdaniels
paulpdaniels

Reputation: 18663

I think I gave this answer a while back on rate limiting.

You can do it with RxJS:

//This would be replaced by whatever your event source was
//I just made it a button click in this case
var source = Rx.Observable.fromEvent($button, 'click')

  //Captures either all the events for one second for a max of 5 events
  //Projects each set into an Observable
  .windowWithTimeOrCount(1000, 5)

  //Only the first window in a single second gets propagated
  //The others will be dropped
  .throttleFirst(1000)

  //Flatten the sequence by concatenating all the windows
  .concatAll()

  //Build the event body now *after* we have done filtering
  .flatMap(function() { 
    //The calendar request api supports promises which are 
    //handled implicitly in Rx by operators like flatMap. As a result
    //this will automatically wait until it receives a response.
    return gapi.client.calendar.events.insert(/*event body*/);
  });

//Process the response
source.subscribe(
  function(response) { console.log('Event successfully created!'); });

Upvotes: 1

Related Questions