Created
October 22, 2019 07:41
-
-
Save jamesknelson/20385aa0aa59bcbdf7d31ac80cacee9f to your computer and use it in GitHub Desktop.
Turn an async function into something you can subscribe to (untested)
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 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