rxjs ajax query,RxJS throttle for AJAX requests

I want to create a function that will make AJAX requests to backend. And if this function is called many times at the same time, then it should not make many identical requests to the server. It must make only 1 request.

For example:

doAJAX('http://example-1.com/').subscribe(res => console.log); // must send a request

doAJAX('http://example-1.com/').subscribe(res => console.log); // must NOT send a request

doAJAX('http://example-2.com/').subscribe(res => console.log); // must send a request, bacause of different URL

window.setTimeout(() => {

doAJAX('http://example-2.com/').subscribe(res => console.log); // must send a request because too much time has passed since the last request

}, 3000)

All function calls should return a result, as if the request was actually made.

I think for this purpose I can use RxJS library.

I have done this:

const request$ = new Subject < string > ();

const response$ = request.pipe(

groupBy((url: string) => url),

flatMap(group => group.pipe(auditTime(500))), // make a request no more than once every 500 msec

map((url: string) => [

url,

from(fetch(url))

]),

share()

);

const doAJAX = (url: string): Observable {

return new Observable(observe => {

response$

.pipe(

filter(result => result[0] === url),

first(),

flatMap(result => result[1])

)

.subscribe(

(response: any) => {

observe.next(response);

observe.complete();

},

err => {

observe.error(err);

}

);

request$.next(url);

});

}

I create request$ subject and response$ observable. doAjax function subscribes for response$ and send URL string to request$ subject. Also there are groupBy and auditTime operators in request$ stream. And filter operator in doAJAX function.

This code works but I think it is very difficult. Is there a way to make this task easier? Maybe RxJS scheduler or not use RxJS library at all

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值