preactjs / signals

Manage state with style in every framework
https://preactjs.com/blog/introducing-signals/
MIT License
3.64k stars 89 forks source link

Adding a callback that will be triggered when the signal starts to be observed #428

Open szagi3891 opened 8 months ago

szagi3891 commented 8 months ago

This callback could behave like this:

const exchangeRate = signal(0,

    // Callback triggered when the signal begins to observe something.
    () => {

        const timer = setTimeout(async () => {

            // Fetch the current exchange rate (of type number) using a request (fetch).
            const currentExchangeRate: number = await fetch( .... );

            // Set the exchange rate signal's value to the current rate.
            exchangeRate.value = currentExchangeRate
        });

        // Callback triggered when the signal stops observing something.
        return () => {

            // Clear the timer.
            clearInterval(timer);
        };
    }
);

For example, MobX implements it like this: https://mobx.js.org/lazy-observables.html

mbeckem commented 1 month ago

The TC39 Signals proposal includes a similar feature:

    interface SignalOptions<T> {
        // Custom comparison function between old and new value. Default: Object.is.
        // The signal is passed in as the this value for context.
        equals?: (this: Signal<T>, t: T, t2: T) => boolean;

        // Callback called when isWatched becomes true, if it was previously false
        [Signal.subtle.watched]?: (this: Signal<T>) => void;

        // Callback called whenever isWatched becomes false, if it was previously true
        [Signal.subtle.unwatched]?: (this: Signal<T>) => void;
    }

watched and unwatched can be used, for example, to start (or stop) observing a foreign data source on demand, only when the signal is actually being used.