Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
szagi3891 opened this issue Oct 31, 2023 · 1 comment

Comments

@szagi3891
Copy link

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
Copy link

mbeckem commented Jun 18, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants