In my Angular application, I am utilizing Observables to set up a WebSocket service. Currently, I have the following implementation:
readwrite(commands: command[]) : Observable<response[]>{
const observable = new Observable((observer)=>{
this.socket.subscribe((socket:WebSocket)=>{
const id = this.uid++;
//// Unsure About This Part ////
this.observerMap[id]={
next: next=>{
observer.next(next);
delete this.observerMap[id]; ////<---- Intended Action
},
error: error=> observer.error(error),
complete: ()=>observer.complete()
}
socket.send(JSON.stringify({requestType:'ReadWrite', commands: commands, id: id}));
});
});
return observable;
}
In the ws.onmessgae
event handler, I handle incoming messages like so:
{
const result = JSON.parse(event.data);
this.observerMap[result.id]?.next(result.commands);
}
While this approach gets the job done, I am exploring cleaner ways to manage these operations. The cleanup of the observableMap[]
cannot be handled within ws.onmessage
due to the existence of observers across multiple messages. Additionally, the cleanup should occur only after the completion of .next()
execution in the Observer, leading me to the current solution. Using .pipe()
triggers execution before the observer completes its operation.
Are there more efficient methods to chain these operations together seamlessly?