Last active
April 12, 2023 21:00
-
-
Save delucis/a35a15030bc82852faf226d9ea248fe9 to your computer and use it in GitHub Desktop.
Simple observable store
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
/** | |
* Simple observable value store. | |
* @template {any} T | |
* @param {T | Promise<T>} initial | |
*/ | |
export function Store(initial) { | |
/** @type {Set<(newValue: T) => void>} */ | |
const subscribers = new Set(); | |
const store = { value: Promise.resolve(initial) }; | |
return { | |
/** @param {T} value */ | |
set(value) { | |
store.value = Promise.resolve(value); | |
subscribers.forEach((callback) => { | |
store.value.then(callback); | |
}); | |
}, | |
get: () => store.value, | |
/** @param {(newValue: T) => void} callback */ | |
subscribe(callback) { | |
subscribers.add(callback); | |
store.value.then(callback); | |
return () => void subscribers.delete(callback); | |
}, | |
}; | |
} |
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
import { Store } from './store.mjs'; | |
const store = Store( | |
fetch('https://api.github.com/orgs/withastro/repos') | |
.then(res => res.json()) | |
); | |
store.subscribe(json => console.log(json)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment