Skip to content

Instantly share code, notes, and snippets.

@Ethan-Arrowood
Created July 2, 2021 19:08
Show Gist options
  • Save Ethan-Arrowood/cfccbd95370fdbdd4fb5aa5512902f3d to your computer and use it in GitHub Desktop.
Save Ethan-Arrowood/cfccbd95370fdbdd4fb5aa5512902f3d 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 ping = () => {
return new Promise((resolve, reject) => {
const r = Math.random()
if (r < 0.5) {
resove()
} else {
reject()
}
})
}
const pingMachine = Machine({
id: 'ping',
initial: 'idle',
states: {
idle: {
on: {
START: 'pinging'
}
},
pinging: {
on: {
STOP: 'idle'
},
invoke: {
id: 'ping',
src: ping,
onDone: {
actions: sendParent('CONNECT'),
target: 'timeout'
},
onError: {
actions: sendParent('DISONNECT'),
target: 'timeout'
}
},
},
timeout: {
on: {
STOP: 'idle'
},
after: {
5000: { target: 'pinging' }
}
}
}
})
const connectionMachine = Machine({
id: 'connection',
initial: 'disconnected',
context: {
ping: null
},
states: {
disconnected: {
entry: assign({
ping: () => spawn(pingMachine)
}),
on: {
'START_PING': {
actions: send({ type: 'START' }, { to: context => context.ping })
},
'STOP_PING': {
actions: send({ type: 'STOP' }, { to: context => context.ping })
},
'CONNECT': {
target: 'connected'
}
}
},
connected: {
on: {
'START_PING': {
actions: send({ type: 'START' }, { to: context => context.ping })
},
'STOP_PING': {
actions: send({ type: 'STOP' }, { to: context => context.ping })
},
'DISCONNECT': {
target: 'disconnected'
}
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment