Skip to content

Instantly share code, notes, and snippets.

@statonjr
Last active September 24, 2020 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save statonjr/16201c4bb9162d144a6cc7e9549bfc6e to your computer and use it in GitHub Desktop.
Save statonjr/16201c4bb9162d144a6cc7e9549bfc6e to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const checkGlobalAPI = (context, event) => {
return new Promise((resolve, reject) => {
let condition = Math.round(Math.random() * 10) > 8;
console.log(condition);
if (condition) {
resolve(42)
} else {
reject('foo')
}
});
}
const checkInternet = (context, event) => {
return new Promise((resolve, reject) => {
let condition = Math.round(Math.random() * 10) > 8;
console.log(condition);
if (condition) {
resolve(42)
} else {
reject('foo')
}
});
}
const retryAPIAllowed = (context, event) => {
return context.apiRetries < 3;
}
const retryInternetAllowed = (context, event) => {
return context.internetRetries < 3;
}
const globalAPIMachine = Machine({
id: 'global-api',
initial: 'checking',
context: {
apiRetries: 0
},
states: {
checking: {
invoke: {
src: checkGlobalAPI,
onDone: {
target: 'done',
actions: [
sendParent('API.ONLINE')
]
},
onError: [
{
target: 'checking',
actions: [
assign({ apiRetries: context => context.apiRetries + 1 })
],
cond: retryAPIAllowed
},
{
target: 'done',
actions: sendParent('API.OFFLINE')
}
]
}
},
done: {
type: 'final'
}
}
});
const internetMachine = Machine({
id: 'internet',
initial: 'checking',
context: {
internetRetries: 0
},
states: {
checking: {
invoke: {
src: checkInternet,
onDone: {
target: 'done',
actions: [
sendParent('INTERNET.ONLINE')
]
},
onError: [
{
target: 'checking',
actions: [
assign({ internetRetries: context => context.internetRetries + 1 })
],
cond: retryInternetAllowed
},
{
target: 'done',
actions: sendParent('INTERNET.OFFLINE')
}
]
}
},
done: {
type: 'final'
}
}
});
const modeMachine = Machine({
id: 'mode',
initial: 'appOffline',
context: {
apiOffline: true,
internetOffline: true
},
states: {
appOffline: {
invoke: {
id: 'global-api',
src: globalAPIMachine
},
on: {
'API.ONLINE': {
target: 'online',
actions: assign({
apiOffline: false,
internetOffline: false
})
},
'API.OFFLINE': {
target: 'apiOffline',
actions: assign({
apiOffline: true
})
}
}
},
apiOffline: {
invoke: {
id: 'internet',
src: internetMachine
},
on: {
'INTERNET.ONLINE': {
target: 'online',
actions: assign({
internetOffline: false
})
},
'INTERNET.OFFLINE': {
target: 'offline',
actions: assign({
apiOffline: true,
internetOffline: true
})
}
}
},
online: {
type: 'final'
},
offline: {
type: 'final'
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment