
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
rxjs-websockets
Advanced tools
An rxjs websocket library with a simple and flexible implementation. Supports the browser and node.js.
Install the dependency:
npm install -S rxjs-websockets
# the following dependency is recommended for most users
npm install -S queueing-subject
import { QueueingSubject } from 'queueing-subject'
import websocketConnect from 'rxjs-websockets'
// this subject queues as necessary to ensure every message is delivered
const input = new QueueingSubject<string>()
// this method returns an object which contains two observables
const { messages, connectionStatus } = websocketConnect('ws://localhost/websocket-path', input)
// send data to the server
input.next('some data')
// the connectionStatus stream will provides the current number of websocket
// connections immediately to each new observer and updates as it changes
const connectionStatusSubscription = connectionStatus.subscribe(numberConnected => {
console.log('number of connected websockets:', numberConnected)
})
// the websocket connection is created lazily when the messages observable is
// subscribed to
const messagesSubscription = messages.subscribe((message: string) => {
console.log('received message:', message)
})
// this will close the websocket
messagesSubscription.unsubscribe()
// closing the websocket does not close the connection status observable, it
// can be used to monitor future connection status changes
connectionStatusSubscription.unsubscribe()
messages
is a cold observable, this means the websocket connection is attempted lazily when a subscription is made to the messages
observable. 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 Angular example below.
This can be done with built-in rxjs operators:
const input = new QueueingSubject<string>()
const { messages, connectionStatus } = websocketConnect(`ws://server`, input)
// try to reconnect every second
messages.pipe(
retryWhen(errors => errors.delay(1000))
).subscribe(message => {
console.log(message)
})
A custom websocket factory function can be supplied that takes a URL and returns an object that is compatible with WebSocket:
const { messages } = websocketConnect(
'ws://127.0.0.1:4201/ws',
this.inputStream = new QueueingSubject<string>(),
undefined,
(url, protocols) => new WebSocket(url, protocols)
)
The API typings follow which show how to use all features including protocols:
export interface Connection {
connectionStatus: Observable<number>
messages: Observable<string>
}
export interface IWebSocket {
close(): any
send(data: string | ArrayBuffer | Blob): any
onopen?: (event: Event) => any
onclose?: (event: CloseEvent) => any
onmessage?: (event: MessageEvent) => any
onerror?: (event: ErrorEvent) => any
}
export declare type WebSocketFactory = (url: string, protocols?: string | string[]) => IWebSocket
export default function connect(
url: string,
input: Observable<string>,
protocols?: string | string[],
websocketFactory?: WebSocketFactory
): Connection
This example shows how to use the map
operator to handle JSON encoding of outgoing messages and parsing of responses:
function jsonWebsocketConnect(url: string, input: Observable<object>, protocols?: string | string[]) {
const jsonInput = input.pipe(map(message => JSON.stringify(message)))
const { connectionStatus, messages } = websocketConnect(url, jsonInput, protocols)
const jsonMessages = messages.pipe(map(message => JSON.parse(message)))
return { connectionStatus, messages: jsonMessages }
}
FAQs
rxjs 7 websockets library
The npm package rxjs-websockets receives a total of 1,876 weekly downloads. As such, rxjs-websockets popularity was classified as popular.
We found that rxjs-websockets demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.