Search code examples
classsveltestoresveltekit

Does a svelte store inside class has to be unsubscribed?


I have a quite large svelteKit project where I use some classes. Inside these classes I use svelte stores.

import { writable, get } from 'svelte/store';

export default class ListController {
    listData = writable([]);

    hasSelection = writable(false);

    unsubscribe = this.listData.subscribe((listDataValue) => {
            this.hasSelection.set(
                listDataValue.some((item) => {
                    return item['selected'] == true;
                })
            );
    });
}

And in +page.svelte:

<script>
    import ListTable from '$lib/Components/ListTable.svelte';
    import ListController from '$lib/Classes/ListController';
    
    let userGroupList = new ListController();
    let { listData, hasChanged } = userGroupList;
</script>

<ListTable {listData} />
<button disabled={$hasChanged}>Delete list entry</button>

If the page is detroyed, is the instance of the ListController and its svelte stores destroyd too? Or do I have to unsubscribe the listData subscribtion (this.listData.subscribe) inside the instance?


Solution

  • If the store is not global/from some outer context as in this case, the last reference to the store should disappear with the page instance and thus everything should ultimately be garbage collected automatically.