watch method

T watch(
  1. BuildContext context
)

Watches a beacon and triggers a widget rebuild when its value changes.

Note: must be called within a widget's build method.

Usage:

final counter = Beacon.writable(0);

class Counter extends StatelessWidget {
 const Counter({super.key});
 @override
 Widget build(BuildContext context) {
   final count = counter.watch(context);
   return Text(count.toString());
 }
}

Implementation

///  @override
///  Widget build(BuildContext context) {
///    final count = counter.watch(context);
///    return Text(count.toString());
///  }
///}
/// ```
T watch(BuildContext context) {
  final key = (hashCode, context.hashCode);

  void rebuildWidget(T value) {
    final record = _subscribers[key]!;

    final target = record.elementRef.target;
    final isMounted = target?.mounted ?? false;

    if (isMounted) {
      target!.markNeedsBuild();
    } else {
      final removedRecord = _subscribers.remove(key);
      removedRecord?.unsub();
    }
  }

  if (!_subscribers.containsKey(key)) {
    final unsub = subscribe(rebuildWidget);

    _subscribers[key] = (
      elementRef: WeakReference(context as Element),
      unsub: unsub,
    );
  }

  _cleanUp();

  return peek();
}