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.

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: () => callback(previousValue as T, peek()),
  );
}