Last active
November 30, 2019 09:14
-
-
Save mattmccray/f41fd2b71c49918c7f818d1b37fce732 to your computer and use it in GitHub Desktop.
Observables: Simple svelte v3 store wrapper that integrates Immer.
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 { derive, readable, writable } from 'svelte/store.js' | |
import { produce } from 'immer' | |
export const update = produce | |
export function computed(deps, reactor) { | |
const source = derive(deps, reactor) | |
return { | |
subscribe: source.subscribe, | |
get snapshot() { return getSnapshot(source) } | |
} | |
} | |
export function stream(generator, value) { | |
const source = readable(generator, value) | |
return { | |
subscribe: source.subscribe, | |
get snapshot() { return getSnapshot(source) } | |
} | |
} | |
export function observable(data) { | |
const store = writable(data); | |
let snapshot = data | |
function update(fn) { store.update(state => snapshot = produce(state, fn)) } | |
function set(data) { store.set(snapshot = data) } | |
return { | |
update, set, | |
subscribe: store.subscribe, | |
get snapshot() { return snapshot }, | |
}; | |
} | |
export function getSnapshot(readable) { | |
let value | |
readable.subscribe((data) => value = data)() | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment