mtyson mtyson - 3 months ago 24
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) => {"ws.onmessage: " + evt);;

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

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

!2 result:

Why? What am I doing wrong?


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 =>;

and then


will work for as many subscribers as you want