mtyson mtyson - 1 month ago 13
TypeScript Question

RxJs Obesrver wrapped around websocket only fires on one subscriber

I am wrapping a websocket in an RxJS observable like so:

this.wsObserver = Observable.create(observer=>{
this.websocket.onmessage = (evt) => {
console.info("ws.onmessage: " + evt);
observer.next(evt);
};
});


This works, but if I add multiple subscribers, only one fires (the last one added):

this.wsObserver.subscribe((result) => {
console.info("! result: " + result);
});
this.wsObserver.subscribe((result) => {
console.info("!2 result: " + result);
});


Only
!2 result:
occurs.

Why? What am I doing wrong?

Answer

The problem is that you overwrite the onmessage handler in your creation handler so only the last subscriber (which is the last to set the onmessage value) is called.

What you could do is:

var var messageSubject = new Subject();
this.websocket.onmessage = (evt => messageSubject.next(evt));

and then

messageSubject.subscribe(...) 

will work for as many subscribers as you want