watchSignal<T> function

T watchSignal<T>(
  1. BuildContext context,
  2. ReadonlySignal<T> signal, {
  3. String? debugLabel,
})

Watch a signal value and rebuild the context of the Element if mounted and mark it as dirty

Implementation

T watchSignal<T>(
  BuildContext context,
  core.ReadonlySignal<T> signal, {
  String? debugLabel,
}) {
  final ctx = context;
  if (ctx.widget is Watch) return signal.value;
  if (ctx is StatefulElement) {
    final state = ctx.state;
    if (state is SignalsMixin) {
      return state.watchSignal(signal);
    }
  }
  if (ctx is Element) {
    final key = ctx.hashCode;
    if (_elementRefs[key] == null) {
      final label = [
        'widget',
        ctx.widget.runtimeType.toString(),
        ctx.widget.hashCode.toString(),
      ].join('=');
      final watcher = ElementWatcher(
        key,
        label,
        WeakReference(ctx),
      );
      _elementRefs[key] = watcher;
      _removeSignalWatchers();
    }
    _elementRefs[key]?.watch(signal);
  }
  // Grab the current value without subscribing
  return signal.peek();
}