angular - How to restrict number of API calls per interval with RxJs? -
i'm developing angular application. , use api provided 1 of social networks , has restriction of 5 api calls per second only.
the direct solution write custom logic count requests , queue them restrictions. if i'm sending 6th request api within 1 second, sent in second after 1st request sent.
but want find elegant solution if it's possible using rxjs.
for instance, can set debounsetime observable in following example. cannot make few requests in row smaller interval 200ms between them.
this.searchcontrol.valuechanges .debouncetime(200) // 200ms ~ 5 requests per second .switchmap(search => this.api.searchpeople(search))
has rxjs techniques can restrict number of emits per interval , queue them in case requests being sent frequently?
you can keep track how many times called api recently. if can make 5 call per second, thant means have 5 tokens, , if token consumed, renewed after second. i've made following operator need:
observable.prototype.ratelimit = function (count: number, slidingwindowtime: number, scheduler = async) { let tokens = count; const tokenchanged = new behaviorsubject(tokens); const consumetoken = () => tokenchanged.next(--tokens); const renewtoken = () => tokenchanged.next(++tokens); const availabletokens = tokenchanged.filter(() => tokens > 0); return this.mergemap(value => availabletokens .take(1) .map(() => { consumetoken(); observable.timer(slidingwindowtime, scheduler).subscribe(renewtoken); return value; })); } declare module 'rxjs/observable' { interface observable < t > { ratelimit(count: number, slidingwindowtime: number, scheduler ? : scheduler): observable < t > } }
Comments
Post a Comment