Created
August 7, 2020 07:23
-
-
Save bluwy/aadd5b91edbc2f2831e45243394851bc to your computer and use it in GitHub Desktop.
Get the current value of subscribable stores, e.g. Svelte stores
This file contains hidden or 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
| /** Callback to inform of a value updates. */ | |
| type Subscriber<T> = (value: T) => void | |
| /** Unsubscribes from value updates. */ | |
| type Unsubscriber = () => void | |
| /** A store that can be subscribed */ | |
| interface Subscribable<T> { | |
| subscribe: (run: Subscriber<T>) => Unsubscriber | |
| } | |
| // Solution 1: WeakMap | |
| const storeMap = new WeakMap() | |
| /** Get the store's current value */ | |
| export function get<T>(store: Subscribable<T>): T { | |
| if (!storeMap.has(store)) { | |
| store.subscribe((v) => storeMap.set(store, v)) | |
| } | |
| return storeMap.get(store) | |
| } | |
| // Solution 2: Manual subscription | |
| /** Utility to auto-subscribe store values */ | |
| export function useGet<T>(store: Subscribable<T>): [() => T, Unsubscriber] { | |
| let value: T | |
| const unsub = store.subscribe((v) => (value = v)) | |
| return [() => value, unsub] | |
| } | |
| // Solution 3: Sub and unsub (Svelte's built-in function) | |
| /** Subscribes and unsubscrines immediately to get the current value */ | |
| export function quickGet<T>(store: Subscribable<T>): T { | |
| let value: T | |
| store.subscribe((v) => (value = v))() | |
| return value | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment