Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@saulshanabrook
Created August 20, 2019 19:06
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 saulshanabrook/a1d8ef98ccc97655fd7681767f10cf7a to your computer and use it in GitHub Desktop.
Save saulshanabrook/a1d8ef98ccc97655fd7681767f10cf7a to your computer and use it in GitHub Desktop.
const addSubscriber = assign({
subscribers: (context, event) => context.subscribers + 1
});
const removeSubscriber = assign({
subscribers: (context, event) => context.subscribers - 1
});
const subscribeParent = assign({
subscription: 'parent subscription'
});
const unsubscribeParent = assign({
subscription: null
});
// Guard to check if the glass is full
function noSubscribers(context, event) {
return context.subscribers === 0;
}
const glassMachine = Machine(
{
id: 'cached-observable',
context: {
subscribers: 0,
subscribtion: null,
},
initial: 'initial',
states: {
initial: {
on: {
SUBSCRIBE: {
target: 'active',
actions: [
'addSubscriber',
'subscribeParent'
]
}
}
},
active: {
on: {
// Transient transition
'': {
target: 'initial',
cond: 'noSubscribers',
actions: ['unsubscribeParent']
},
NEXT: {
target: 'active'
},
ERROR: {
target: 'done'
},
COMPLETE: {
target: 'done'
},
SUBSCRIBE: {
target: 'active',
actions: 'addSubscriber'
},
UNSUBSCRIBE: {
target: 'active',
actions: "removeSubscriber"
}
}
},
done: {
on: {
SUBSCRIBE: {
target: 'done',
actions: 'addSubscriber'
},
UNSUBSCRIBE: {
target: 'done',
actions: "removeSubscriber"
}
}
}
}
},
{
actions: { addSubscriber, removeSubscriber },
guards: { noSubscribers }
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment