检测何时不再使用 svelte store

Detect when svelte store is not used anymore

我正在通过封装一个精巧的可写存储来创建一个自定义的精巧存储。

我想检测该商店何时未被任何组件订阅;当订阅数为 0

我的 objective 是清除一些在没有人使用时绑定到自定义商店的大量外部资源 (websockets)。

目前,我正在通过环绕 subscribe( ) 方法来计算订阅和取消订阅。 它按预期工作。但对我来说这看起来像是一个讨厌的黑客。

我的问题:在 Svelte 中是否有标准/干净的方法来实现此行为?

如果不是,有更多 Javascipt 和 svelte 经验的人可以确认这是否合法吗?

演示时间:https://svelte.dev/repl/f4e24fb5c56f457a94bf9cf645955b9f?version=3.43.1

import { writable } from 'svelte/store';

// Instanciate the store
export let store = MakeStore();

// By design, I want a function that returns a custom svelte store
export function MakeStore(initialValue = null) {

        const { subscribe, set, update } = writable(initialValue);

        let subscribercount = 0;

        let wsubscribe = function (run, callback) {
            subscribercount++;
            console.log("subscribercount++", subscribercount);

            let wunsubscribe = subscribe(run, callback);
            return () => {
                subscribercount--;
                console.log("subscribercount--", subscribercount);

                if (subscribercount == 0) {

                    // -------------------------------
                    // Free up resources
                    // I want a clean way to get here
                    // -------------------------------
                    console.log("Cleaning up...");
                }
                return wunsubscribe();
            }
        }

        // Some external calls here

        let store = {
            subscribe: wsubscribe,
            set: newvalue => {
                set(newvalue);
                // Some external calls here
            },
            update: update
        };

        // Some external calls here

        return store;
    }


是的,它内置于商店中并记录在案here

来自文档

If a function is passed as the second argument, it will be called when the number of subscribers goes from zero to one (but not from one to two, etc). That function will be passed a set function which changes the value of the store. It must return a stop function that is called when the subscriber count goes from one to zero.

所以你会这样做,例如:

const count = writable(0, () => {
    console.log('got a subscriber');
    return () => console.log('no more subscribers');
});