Created
June 26, 2020 12:32
-
-
Save AlCalzone/030876615936dd06318d28b2e9596f79 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const sendMsg = data => { | |
return new Promise((resolve, reject) => { | |
console.log(`send ${data}`); | |
setTimeout(() => { | |
if (Math.random() < 0.6) resolve(); | |
else reject(); | |
}, 1000); | |
}); | |
} | |
const mayRetry = ctx => ctx.controllerAttempts < 3; | |
const serialWrite = Machine({ | |
id: 'serialWrite', | |
initial: 'idle', | |
context: { | |
controllerAttempts: 0, | |
data: "abc", | |
}, | |
states: { | |
idle: { | |
on: { | |
SEND: { | |
target: 'sending', | |
actions: [ | |
assign({data: (ctx,evt) => evt.data}) | |
] | |
} | |
} | |
}, | |
sending: { | |
entry: assign({ | |
controllerAttempts: ctx => ctx.controllerAttempts + 1 | |
}), | |
invoke: { | |
id: 'sendMsg', | |
src: (context) => sendMsg(context.data), | |
onDone: { | |
target: 'waitForAck', | |
}, | |
onError: { | |
target: 'retry', | |
} | |
} | |
}, | |
waitForAck: { | |
on: { | |
ACK: 'success', | |
CAN: 'retry', | |
TIMER: 'retry' | |
} | |
}, | |
success: { | |
type: 'final' | |
}, | |
retry: { | |
on: { | |
'': [ | |
{target: 'sending', cond: mayRetry}, | |
{target: 'failure' } | |
] | |
} | |
}, | |
failure: { | |
type: 'final' | |
} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment