Skip to content

Instantly share code, notes, and snippets.

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