Created
February 26, 2021 08:09
-
-
Save hackape/fa09fcfd9b60e3475a361ca69af362b2 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const wsMachine = Machine( | |
{ | |
initial: 'idle', | |
context: { | |
ws: null, | |
}, | |
states: { | |
idle: { | |
on: { | |
CONNECT: 'connecting', | |
}, | |
}, | |
connecting: { | |
invoke: { | |
src: 'createWsInstance', | |
onDone: { | |
target: 'connected', | |
actions: assign({ ws: (ctx, evt) => evt.data }), | |
}, | |
}, | |
}, | |
connected: { | |
activities: [''], | |
}, | |
}, | |
}, | |
{ | |
activities: { | |
handleMessages: ctx => { | |
const onMessage = ev => { | |
console.log(ev.data) | |
} | |
ctx.ws.addEventListener('message', onMessage) | |
return () => { | |
ctx.ws.removeEventListener('message', onMessage) | |
} | |
}, | |
}, | |
services: { | |
createWsInstance: (ctx, evt) => { | |
return new Promise((resolve, reject) => { | |
const ws = new WebSocket(evt.data.url) | |
ws.addEventListener( | |
'open', | |
ev => { | |
resolve(ws) | |
}, | |
{ once: true } | |
) | |
}) | |
}, | |
}, | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment