Consider this Svelte store and subscription code snippet. What will be logged to the console?
import { writable } from 'svelte/store'; const count = writable(0); const unsubscribe = count.subscribe(value => { console.log('Count is', value); }); count.set(5); unsubscribe(); count.set(10);
Remember what happens when you call the unsubscribe function.
The subscription callback runs immediately with the initial value (0), then again when set(5) is called. After unsubscribe(), the callback no longer runs, so set(10) does not trigger a log.
Which of the following custom store implementations correctly follows the Svelte store contract by providing a subscribe method?
The subscribe method must return an unsubscribe function.
Option A returns a function from subscribe, which is the unsubscribe function. Options B and C do not return anything, and D returns null instead of a function, which breaks the contract.
Examine the code below. Why does it cause a runtime error when subscribing?
function brokenStore() { let value = 0; return { subscribe: (run) => { run(value); return null; } }; } const store = brokenStore(); const unsub = store.subscribe(val => console.log(val)); unsub();
Check what the unsubscribe variable holds after subscribing.
The subscribe method must return a function to unsubscribe. Returning null means unsub is null, so calling unsub() throws a TypeError.
Given this Svelte writable store and subscriptions, what is the console output?
import { writable } from 'svelte/store'; const num = writable(1); const unsub1 = num.subscribe(v => console.log('Sub1:', v)); num.set(2); const unsub2 = num.subscribe(v => console.log('Sub2:', v)); num.set(3); unsub1(); num.set(4); unsub2(); num.set(5);
Remember which subscriptions are active after each unsubscribe call.
Initially, Sub1 logs 1. After set(2), Sub1 logs 2. Sub2 subscribes and immediately logs 2. After set(3), both Sub1 and Sub2 log 3. unsub1() removes Sub1, so set(4) only triggers Sub2. unsub2() removes Sub2, so set(5) triggers no logs.
Choose the best description of the subscribe method's role in Svelte stores.
Think about how components react to store changes.
The subscribe method lets code listen for changes by registering a callback. It also returns an unsubscribe function to stop listening. It does not update values or create stores.