Created
August 20, 2019 19:06
-
-
Save saulshanabrook/a1d8ef98ccc97655fd7681767f10cf7a to your computer and use it in GitHub Desktop.
This file contains 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 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