DEV Community

TK
TK

Posted on

1 1

What is unsubscribe in Sveletekit?

When I tried to create persited store in SvelteKit, I had to understand unscribe function like below.

<script>
    import { onDestroy } from 'svelte'
    import { writable } from 'svelte/store';

    const count = writable(0, () => {
        console.log('Start subscribing')
                // Below function is called when execute unsubscribe function.
        return () => console.log('Stop subscribing');
    })

    const increment = () => count.update(value => {
        return value + 1
    })

    const unsubscribe = count.subscribe(value => {
        console.log(value)
    })

        onDestroy(unsubscribe)
</script>

<button on:click={increment}>
    Increment
</button>
<button on:click={unsubscribe}>
    Stop subscribe
</button>
Enter fullscreen mode Exit fullscreen mode

What is unsubscribe function?

If we use subscribe, we should stop the subscribing. Because when component is died, we cannot stop it and use lots of memory. So we should call unsubscribe function with onDestory function. But it is too trouble to develop... ... so we can use $ prefix as instead.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs