Skip to content

Instantly share code, notes, and snippets.

@tmbritton
Last active May 2, 2021 01:01
Show Gist options
  • Save tmbritton/46d79ddd7f6f80f49104e65ca68ac105 to your computer and use it in GitHub Desktop.
Save tmbritton/46d79ddd7f6f80f49104e65ca68ac105 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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