Skip to content

Instantly share code, notes, and snippets.

@jamesknelson
Created October 22, 2019 07:41
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 jamesknelson/20385aa0aa59bcbdf7d31ac80cacee9f to your computer and use it in GitHub Desktop.
Save jamesknelson/20385aa0aa59bcbdf7d31ac80cacee9f to your computer and use it in GitHub Desktop.
Turn an async function into something you can subscribe to (untested)
const requests = {}
export const createSubscribe = (asyncFn) => {
return subscribeToData = (params, onUpdate) => {
onUpdate('pending')
const key = JSON.stringify(params)
const request = requests[key]
if (!request) {
request = requests[key] = {
promise: asyncFn(params),
count: 1,
}
}
else {
request.count++
}
request.promise.then(
data => onUpdate('received', data)
error => onUpdate('error')
)
return () => {
onUpdate = () => {}
if (--request.count === 0) {
delete requests[key]
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment