Send a message with rxjs webSocket on each new connection

Viewed 490

Using rxjs/webSocket, how do I send a login message on each new connection? Seems that the simplest way to do it would be using WebSocketSubjectConfig, hook on to the openObserver, dig out the underlying webSocket from event.target and send the login message. Is it recommended? Is there a better way? (using angular, but I don't think it matters).

Here's my code:

ws = webSocket({
    url: "wss://example.com",      
    openObserver: {
      next: (e) => e.target.send("login-info")          
    }
})
1 Answers

You can use webSocket(config).multiplex(() => 'login-info', () => null, () => true) to create a multiplexed WebsocketSubject which sends a message on subscription.

This feature was originally intended to support multiple streams/topics on one single Websocket, but I think it's fine to use it for your use-case as well.

Related