An rxjs websocket library with a simple and flexible implementation. Supports the browser and node.js.
Comparisons to other rxjs websocket libraries:
- observable-socket provides an input subject for the user, rxjs-websockets allows the user to supply the input stream as a parameter to allow the user to select an observable with semantics appropriate for their own use case (queueing-subject can be used to achieve the same semantics as observable-socket).
- With observable-socket the WebSocket object must be used and managed by the user, rxjs-websocket manages the WebSocket(s) for the user lazily according to subscriptions to the messages observable.
- With observable-socket the WebSocket object must be observed using plain old events to detect the connection status, rxjs-websockets presents the connection status through observables.
- rxjs built-in websocket subject
- Implemented as a Subject so lacks the flexibility that rxjs-websockets and observable-socket provide.
- Does not provide any ability to monitor the web socket connection state.
npm install -S rxjs-websockets# oryarn add rxjs-websockets
// this subject queues as necessary to ensure every message is delivered// queue up a request to be sent when the websocket connectsinput$.next'some data'// create the websocket observable, does *not* open the websocket connectionsetTimeoutcloseWebsocket, 2000
The observable returned by
makeWebSocketObservable is cold, this means the websocket connection is attempted lazily as subscriptions are made to it. Advanced users of this library will find it important to understand the distinction between hot and cold observables, for most it will be sufficient to use the share operator as shown in the example above. The
share operator ensures at most one websocket connection is attempted regardless of the number of subscriptions to the observable while ensuring the socket is closed when the last subscription is unsubscribed. When only one subscription is made the operator has no effect.
By default the websocket supports binary messages so the payload type is
string | ArrayBuffer | Blob, when you only need
string messages the generic parameter to
makeWebSocketObservable can be used:
Reconnecting on unexpected connection closures
This can be done with the built-in rxjs operator
Alternate WebSocket implementations
A custom websocket factory function can be supplied that takes a URL and returns an object that is compatible with WebSocket:
JSON messages and responses
This example shows how to use the
map operator to handle JSON encoding of outgoing messages and parsing of responses:
The function above can be used identically to
makeWebSocketObservable only the requests/responses will be transparently encoded/decoded.