Skip to content

Instantly share code, notes, and snippets.

@dualcyclone
Created November 8, 2018 11:05
Show Gist options
  • Save dualcyclone/20af589c3c29161726a933c4d72ad0f1 to your computer and use it in GitHub Desktop.
Save dualcyclone/20af589c3c29161726a933c4d72ad0f1 to your computer and use it in GitHub Desktop.
WebSocket with readyState$ and readyState utility streams
import { interval } from 'rxjs'
import { distinctUntilChanged, mapTo, share } from 'rxjs/operators'
export const WEBSOCKET_READYSTATES = {
NOOP: null, // Unused in example, but useful to identify when a websocket doesn't exist (ie, not operational)
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3
}
export class Websocket extends WebSocket {
get readyState$() {
return interval(1).pipe(
mapTo(this.readyState),
distinctUntilChanged(),
share()
)
}
get connecting$() {
return this.readyState$.pipe(
filter(readyState => readyState === WEBSOCKET_READYSTATES.CONNECTING)
)
}
get open$() {
return this.readyState$.pipe(
filter(readyState => readyState === WEBSOCKET_READYSTATES.OPEN)
)
}
get closing$() {
return this.readyState$.pipe(
filter(readyState => readyState === WEBSOCKET_READYSTATES.CLOSING)
)
}
get closed$() {
return this.readyState$.pipe(
filter(readyState => readyState === WEBSOCKET_READYSTATES.CLOSED)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment