Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.