Created
July 11, 2021 12:32
-
-
Save qmzik/351e06fa7dc0bbb714968b1d6fa75dbb to your computer and use it in GitHub Desktop.
This file contains 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
const source = (subscriber: Observer<string>) => { | |
const socket = new WebSocket('wss://echo.websocket.org'); | |
socket.onopen = () => { | |
socket.send('Hello, World!'); | |
}; | |
socket.onmessage = (e) => { | |
subscriber.next(e.data); | |
}; | |
socket.onclose = (e) => { | |
if (e.wasClean) { | |
subscriber.complete(); | |
} else { | |
subscriber.error(new Error('Socket closed dirty!')); | |
} | |
}; | |
return () => { | |
if (socket.readyState <= WebSocket.OPEN) { | |
socket.close(); | |
} | |
}; | |
}; | |
const teardown = source({ | |
next: console.log, | |
complete: () => console.log('done'), | |
error: console.error, | |
}); | |
// Decide you really don't want to keep the socket open. | |
teardown(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment