Skip to content

The signal graph protocol should be exposed for novel implementations #258

Open
@DavidANeil

Description

@DavidANeil

Most of the heavy work in the Signal graph is done in what I am calling "protocol functions", and a common interface.

If these protocol functions were exposed to JS, then implementations with varying behavior could be implemented.

One goal here is that an implementation of State, Computed, and Watcher could be implemented in JS, with only minor performance degradation, as most of the graph logic would still be handled in native code.

This would allow the spec to remain narrow in scope while still allowing variations by users for efficiency.

As an example of this, imagine a reactive node that starts out as one value, and may eventually change to a different value, but once it changes once it will never change again. If appropriate protocol functions were exposed, then a compliant implementation could look like this:

export class ReactiveOneShot<T> implements ReactiveProducer<T> {
    public valueVersion = 1;

    public checkForActuallyChangedValue(): void {
        // Do nothing. We know exactly when we have changed.
    }

    #flipped = false;
    #value: T;

    constructor(value: T) {
        this.#value = value;
    }

    public get() {
        if (!this.#flipped) {
            Signal.protocol.producerAccessed(this);
        }
        return this.#value;
    }

    public shoot(finalValue: T) {
        if (!this.#flipped) {
            this.#flipped = true;
            this.#value = finalValue;
            ++this.valueVersion;
            Signal.protocol.producerNotifyConsumers(this);
        } else {
            throw new Error('ReactiveOneShot already finalized');
        }
    }
}

While this example is possible without any of the protocol being exposed, it requires creating and (hopefully) throwing away a bit more memory:

export class ReactiveOneShotNoProtocol<T> {
    #finalValue: T | undefined = undefined;
    #state: Signal.State<T> | undefined;

    constructor(value: T) {
        this.#state = new Signal.state(value);
    }

    public get() {
        if (this.#state) {
            return this.#state.get()
        } else {
            return this.#finalValue as T;
        }
    }

    public shoot(finalValue: T) {
        if (this.#state) {
            this.#finalValue = finalValue;
            this.#state.set(finalValue);
            this.#state = undefined;
        } else {
            throw new Error('ReactiveOneShot already finalized');
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions