trackWithEffect<T> function

T trackWithEffect<T>(
  1. T fn(),
  2. EffectNode sub, [
  3. bool purge = true
])

Executes a function with a specific effect node as the active subscriber.

This function temporarily sets the given reactive node as the active subscriber, allowing it to track dependencies accessed within the function. This is useful for manually controlling dependency tracking in advanced scenarios.

Parameters:

  • fn: Function to execute with the specified subscriber
  • sub: The effect node to use as the active subscriber
  • purge: Whether to purge dependencies after execution

Returns: The result of the function execution

Example:

final customNode = EffectNode();
final result = trackWith(() {
  return signal.value; // Tracked by customNode
}, customNode);

Implementation

@pragma("vm:prefer-inline")
@pragma("wasm:prefer-inline")
@pragma("dart2js:prefer-inline")
T trackWithEffect<T>(T Function() fn, EffectNode sub, [bool purge = true]) {
  final effectNode = sub as ReactiveNode;
  if (purge) {
    ++cycle;
    effectNode.depsTail = null;
  }
  final prevSub = setActiveSub(effectNode);
  try {
    return fn();
  } finally {
    setActiveSub(prevSub);
    if (purge) {
      effectNode.flags = ReactiveFlags.watching;
      purgeDeps(effectNode);
    }
  }
}