observe method

void observe(
  1. BuildContext context,
  2. ObserverCallback<T> callback
)

Observes the state of a beacon and triggers a callback with the current state.

The callback is provided with the current state of the beacon and a BuildContext. This can be used to show snackbars or other side effects.

Conditional observing is not supported: once a widget starts observing a beacon, the callback keeps firing until the beacon is disposed or the widget is unmounted (see watch).

Usage:

final exampleBeacon = Beacon.writable("Initial State");

class ExampleWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    context.observe(exampleBeacon, (state, context) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(state)),
      );
    });
    return Container();
  }
}

Implementation

void observe(BuildContext context, ObserverCallback<T> callback) {
  final key = Object.hash(
    identityHashCode(context),
    'isObserving', // create 1 subscription for each widget
  );

  _watchOrObserve(
    key,
    context,
    callback: () {
      final prev = previousValue;
      if (prev is T) {
        callback(prev, peek());
      }
    },
  );
}