Created
September 27, 2019 21:37
-
-
Save liamross/a6d97f822fd7e9802d5f183abc13f3c1 to your computer and use it in GitHub Desktop.
Documenting the pattern I liked in React's useSubscription hook.
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
// 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