Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Last active November 30, 2019 09:14
Show Gist options
  • Save mattmccray/f41fd2b71c49918c7f818d1b37fce732 to your computer and use it in GitHub Desktop.
Save mattmccray/f41fd2b71c49918c7f818d1b37fce732 to your computer and use it in GitHub Desktop.
Observables: Simple svelte v3 store wrapper that integrates Immer.
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