Search code examples
solid-js

In solidjs, what is the logic behind that determines whether the containing function will become an observer when a signal is read?


When you call the signal's getter function, the containing function become an observer of that signal, e.g.,

const double = () => count() * 2;

Then the "double" function will re-run when count changes.

But in an action or event handler, we may also call the signal's getter function, however the containing function will NOT become an observer of that signal, e.g.,

  const set = () => setCount1(count() + 1);

The "set" function will NOT re-run when count changes.

What is the logic behind that determines whether the containing function will become an observer when a signal is read?

https://playground.solidjs.com/anonymous/c75bf75f-87e8-4939-a103-79e930bf889b


Solution

  • The createEffect function creates an observer and pushes this observer onto a variable before reading a signal. When the signal is read, signal pulls this observer knowing its is a subscriber:

    let currentScope;
    
    function creatEffect((fn, value) => {
       // Here goes the implementation detail
       currentScope = createComputation({ fn, value });
    });
    
    function createSignal(value) {
      const subscribers = new Set();
    
      const read = () => {
        // Here signal captures an observer
        subscribers.add(currentScope);
        return value;
      }
      
      const setter = (nextValue) => {
        value = nextValue;
        // Notify subscribers
        // Subscribers are removed once they are notified
      }
    
      return [getter, setter];
    }
    

    When the signal updates, each subscriber will be called again.

    const [count, setCount] = createSignal(0);
    const double = () => count() * 2;
    
    createEffect(() => {
      console.log(double());
    });
    

    Make no mistake, it is not the double function but the effect that reads the double function is called when the signal updates.

    So, when double is called inside an effect, effect will subscribe to the signals that double contains. When those signals update, the effect re-runs, returning an accurate result.