Skip to content

Instantly share code, notes, and snippets.

@sbaechler
Last active March 23, 2021 09:12
Show Gist options
  • Save sbaechler/f3d1c7e93e181830b4a4b4edc8b9f9e5 to your computer and use it in GitHub Desktop.
Save sbaechler/f3d1c7e93e181830b4a4b4edc8b9f9e5 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const connectMachine = Machine(
{
id: 'websocket',
initial: 'idle',
context: {
retries: 0,
subscriptions: [],
queue: [],
},
states: {
idle: {
on: {
CONNECT: 'connecting',
SUBSCRIBE: {
target: 'connecting',
actions: ['queueSubscription'],
},
},
},
connecting: {
on: {
CONNECTED: 'active',
CONNECTION_LOST: 'connectionLost',
DISCONNECT: 'idle',
SUBSCRIBE: {
actions: ['queueSubscription'],
},
},
},
active: {
entry: ['dequeueSubscriptions'],
on: {
DISCONNECT: 'idle',
CONNECTION_LOST: {
target: 'connectionLost',
actions: assign({
queue: (context) => context.subscriptions,
subscriptions: [],
})
},
SUBSCRIBE: {
actions: ['subscribe'],
},
},
},
connectionLost: {
on: {
always: [
{
target: 'connecting',
cond: 'shouldRetry',
actions: assign({
retries: (context, event) => context.retries + 1,
}),
},
{ target: 'error' },
],
},
},
error: {
final: true,
},
},
},
{
actions: {
subscribe: (context) => {
// In reality this is async and needs a second action.
context.subscriptions.push('subscription')
},
queueSubscription: (context) => {
context.queue.push('subscription')
},
dequeueSubscriptions: (context) => {
context.subscriptions.push(...context.queue)
context.queue = [];
},
},
guards: {
shouldRetry: (context) => context.retries < 3,
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment