Skip to content

Instantly share code, notes, and snippets.

@liamross
Created September 27, 2019 21:37
Show Gist options
  • Save liamross/a6d97f822fd7e9802d5f183abc13f3c1 to your computer and use it in GitHub Desktop.
Save liamross/a6d97f822fd7e9802d5f183abc13f3c1 to your computer and use it in GitHub Desktop.
Documenting the pattern I liked in React's useSubscription hook.
// https://github.com/facebook/react/blob/master/packages/use-subscription/src/useSubscription.js
type Subscription<Value> = () => {
getValue: () => Value;
subscribe: (callback: Function) => () => void;
};
const subscription: Subscription<string> = () => ({
getValue: () => something.value,
subscribe: callback => {
// Subscribe the subscriber that triggered this function.
something.subscribe(callback);
// Return the unsubscription function to the subscriber for use whenever.
return () => something.unsubscribe(callback);
},
});
let value = '';
const subscriber = () => {
const {getValue, subscribe} = subscription();
value = getValue();
const callback = () => {
value = getValue();
};
const unsubscribe = subscribe(callback);
// Whenever you want to unsubscribe:
unsubscribe();
// Or even return for external use:
return () => unsubscribe();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment