From 65e65154a792bcd5bea3e829cd5fa63332c07816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Marche?= <35939574+Marr11317@users.noreply.github.com> Date: Tue, 6 Apr 2021 01:35:09 -0400 Subject: [PATCH] [store] Make writable depend on readable ...and add get function to stores. The first part came along trying to fix the second one. I just noticed how it was and decided the fix was easy enough. I did not run any test and actually coded that inside github's default editor, and it's my first contribution to Svelte, so please excuse me if this PR is completely useless/stupid. Reason for the PR: The current `get(store)` access function is (inefficient)[https://svelte.dev/docs#get] (see the warning) and not object oriented. Fix: The easy fix is to add a `get` accessor for the readable's value. --- src/runtime/store/index.ts | 54 ++++++++++++++++++++++---------------- 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/src/runtime/store/index.ts b/src/runtime/store/index.ts index 45877d861f..6abb014553 100644 --- a/src/runtime/store/index.ts +++ b/src/runtime/store/index.ts @@ -23,6 +23,11 @@ export interface Readable { * @param invalidate cleanup callback */ subscribe(this: void, run: Subscriber, invalidate?: Invalidator): Unsubscriber; + + /** + * Get the readable's current value. + */ + get(): T; } /** Writable interface for both updating and subscribing. */ @@ -51,8 +56,33 @@ const subscriber_queue = []; * @param {StartStopNotifier}start start and stop notifications for subscriptions */ export function readable(value: T, start: StartStopNotifier): Readable { + + function subscribe(run: Subscriber, invalidate: Invalidator = noop): Unsubscriber { + const subscriber: SubscribeInvalidateTuple = [run, invalidate]; + subscribers.push(subscriber); + if (subscribers.length === 1) { + stop = start(set) || noop; + } + run(value); + + return () => { + const index = subscribers.indexOf(subscriber); + if (index !== -1) { + subscribers.splice(index, 1); + } + if (subscribers.length === 0) { + stop(); + stop = null; + } + }; + } + + function get(): T { + return value; + } + return { - subscribe: writable(value, start).subscribe + subscribe }; } @@ -89,27 +119,7 @@ export function writable(value: T, start: StartStopNotifier = noop): Writa set(fn(value)); } - function subscribe(run: Subscriber, invalidate: Invalidator = noop): Unsubscriber { - const subscriber: SubscribeInvalidateTuple = [run, invalidate]; - subscribers.push(subscriber); - if (subscribers.length === 1) { - stop = start(set) || noop; - } - run(value); - - return () => { - const index = subscribers.indexOf(subscriber); - if (index !== -1) { - subscribers.splice(index, 1); - } - if (subscribers.length === 0) { - stop(); - stop = null; - } - }; - } - - return { set, update, subscribe }; + return { set, update, subscribe: readable(value, start).subscribe }; } /** One or more `Readable`s. */