Currently, I am using BehaviorSubject to receive data and also utilizing websockets, although the websocket functionality is not relevant at this moment. The main issue I am facing is why I keep receiving duplicated messages from BehaviorSubject.
When examining the code in the service:
hubMessage$ = new BehaviorSubject({});
public startConnection = (id: number) => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('https://api/hub')
.build();
this.hubConnection
.start()
.then(() => {
console.log('connection established')
}
)
.catch(err => {
console.log('Error while starting connection: ' + err)
this.retryConnection();
})
}
public newLocationRecieved() {
this.hubConnection.on('NewLoc', (data) => {
console.log('new location recieved' , data)
this.hubMessage$.next(data);
})
}
public sendDriverId(id: number = 1) {
this.hubConnection.send('SubOnDriver', { driverId: id })
}
Every 20 seconds, a new location update is received. I need to prevent previous data from accumulating in hubMessage, as it causes my software to crash after one minute due to duplicate messages.
Imagine if every message you received was duplicated exponentially: one first, then two, then four, then sixty..32....64...
Why is this happening?
How can this issue be resolved?
In the component, I use this message as follows:
Component code:
ngOnChanges() {
this.dispatchDetails;
this.createMarkers();
}
createMarkers() {
console.log('Connection started right now ', this.dispatchDetails)
this.newCoordinate();
}
private newCoordinate = () => {
this.signalRService.hubMessage$.subscribe(
(data: any) => {
console.log('received new coordinate ?', data); // HERE I AM RECEIVING TOO MANY DUPLICATE MESSAGES
this.signalRService.newLocationRecieved()
this.locationCoords = data;
if (this.locationCoords.location) {
this.latitude = this.locationCoords?.location?.latitude
this.longitude = this.locationCoords?.location?.longitude
}
}
)
}
I may need to clear my variable or perhaps there is an issue with the websocket connection?
Is the websocket connection possibly causing duplicates, which seems unlikely?
You probably understand that creating a minimal reproduction code for web sockets is challenging...