Created
November 8, 2018 11:05
-
-
Save dualcyclone/20af589c3c29161726a933c4d72ad0f1 to your computer and use it in GitHub Desktop.
WebSocket with readyState$ and readyState utility streams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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