listenSignal<T> function

void listenSignal<T>(
  1. BuildContext context,
  2. ReadonlySignal<T> signal,
  3. void callback(), {
  4. String? debugLabel,
})

Used to listen for updates on a signal but not rebuild the nearest element

final counter = signal(0);
...
@override
Widget build(BuildContext context) {
  listenSignal(context, counter, () {
    if (counter.value == 10) {
      final messenger = ScaffoldMessenger.of(context);
      messenger.hideCurrentSnackBar();
      messenger.showSnackBar(
        const SnackBar(content: Text('You hit 10 clicks!')),
      );
    }
  });
...
}

Implementation

void listenSignal<T>(
  BuildContext context,
  ReadonlySignal<T> signal,
  void Function() callback, {
  String? debugLabel,
}) {
  if (context is Element) {
    final key = context.hashCode;
    if (_elementRefs[key] == null) {
      final watcher = ElementWatcher(key, WeakReference(context));
      _elementRefs[key] = watcher;
      _init();
    }
    _elementRefs[key]?.listen(signal, callback);
  }
}