Skip to content

Instantly share code, notes, and snippets.

@delucis
Last active April 12, 2023 21:00
Show Gist options
  • Save delucis/a35a15030bc82852faf226d9ea248fe9 to your computer and use it in GitHub Desktop.
Save delucis/a35a15030bc82852faf226d9ea248fe9 to your computer and use it in GitHub Desktop.
Simple observable store
/**
* 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);
},
};
}
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