I have a module where the client listens to websocket events from the server, and every time an update event is received, a HTTP call is made to update the data set on the UI. I am running into a problem, where for a certain type of operation, the server send about 40 update events within a span of 10 seconds and the UI triggers 40 API calls in the span of 10s. The server does not seem able to process all these requests.
I was wondering if there is an rxjs way to handle this problem where, when an API call to the server is still pending for the same request, I have to wait for it to complete before I make the same request again.
listen(wstopic) {
return this.wsService.subscribeEndPoint(wstopic).pipe(
switchMap((event) => {
if (event === 'UPDATE') {
return this.http.get(`${this.baseUrl}/monitoring/eventlog`, { params })
} else {
return of(null)
}
})
)
}
listen('some/topic').subscribe((data) => {
if(data) {
// Append data to array
}
});
I want this part to be called, only if this same call is not already in progress
if (event === 'UPDATE') {
return this.http.get(`${this.baseUrl}/monitoring/eventlog`, { params })
}
Is there a way to achieve this with rxjs?
CodePudding user response:
You could have a look on exhaustMap
instead of that switchMap
. switchMap
always change to the newest emission from the source, exhaustMap
on the other side will stick with one emission until it's finished and then will go ahead with another one.
CodePudding user response:
You can use distinctUntilChanged
with a custom comparer function to emit when the current value is different than the last one:
For example:
const yourBackendData$ = from([
{ id: 1 },
{ id: 2 },
{ id: 2 },
{ id: 3 }
]);
yourBackendData$.pipe(
distinctUntilChanged((prev, curr) => prev.id === curr.id))
.subscribe(console.log);
// output:
// {id: 1}, {id: 2}, {id: 3}
You can read more about it here