Last active
May 2, 2021 01:01
-
-
Save tmbritton/46d79ddd7f6f80f49104e65ca68ac105 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
const pubsubMachine = Machine({ | |
id: 'pubsub', | |
initial: 'listening', | |
type: 'parallel', | |
context: { | |
queue: [], | |
subscriptions: {}, | |
}, | |
states: { | |
listening: { | |
on: { | |
PUBLISH: { | |
actions: ['addItemToQueue', send('ITEM_ADDED_TO_QUEUE', { | |
to: (context) => context.processorMachineRef | |
})] | |
}, | |
SUBSCRIBE: { | |
actions: ['addSubscription'] | |
}, | |
}, | |
}, | |
queueProcessor: { | |
initial: 'idle', | |
states: { | |
idle: { | |
on: { | |
ITEM_ADDED_TO_QUEUE: 'processing' | |
} | |
}, | |
processing: { | |
entry: ['dispatch'], | |
on: { | |
ITEM_PROCESSED: 'processed' | |
} | |
}, | |
processed: { | |
type: 'final', | |
entry: 'removeItemFromQueue', | |
on: { | |
always: [ | |
{ target: 'processing', cond: 'hasItemInQueue' }, | |
{ target: 'idle' } | |
] | |
} | |
} | |
} | |
} | |
}, | |
}, { | |
actions: { | |
addItemToQueue: (context, event) => { | |
assign({ | |
queue:(context, event) => [...context.queue, event.payload.dispatch] | |
}) | |
}, | |
addSubscription: () => { | |
assign({ | |
subscriptions: (context, event) => { | |
const subscriptions = [...context.subscriptions]; | |
if (!subscriptions[event.type]) { | |
subscriptions[event.type] = []; | |
} | |
return { | |
...subscriptions, | |
[event.type]: [ | |
...subscriptions[event.type], | |
event.payload.ref | |
] | |
} | |
} | |
}) | |
}, | |
dispatch: (context, event) => { | |
context?.subscriptions?.foreach((subscription) => { | |
if (subscription.type === event.type) { | |
subscription?.ref?.send(event); | |
} | |
}); | |
send('ITEM_PROCESSED'); | |
}, | |
removeItemFromQueue: (context, event) => { | |
assign({ | |
queue:(context, event) => context.queue.slice(1), | |
}) | |
}, | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment