Observer

A purchase is placed, and several things must happen: a confirmation mail, a stock update, loyalty points. The Observer pattern keeps the purchase code unaware of who reacts. This page shows it in plain Dart and in Spring for Dart, and what it takes to add one more listener.

The examples share this class:

class Purchase {
  const Purchase(this.id, this.email, this.total);
  final String id;
  final String email;
  final double total;
}

The listeners

Plain Dart, a listener list. The service keeps a list, and someone has to fill it.

abstract interface class PurchaseListener {
  void onPlaced(Purchase purchase);
}

class Checkout {
  final _listeners = <PurchaseListener>[];

  void addListener(PurchaseListener listener) => _listeners.add(listener);

  void place(Purchase purchase) {
    // ... save the purchase
    for (final listener in _listeners) {
      listener.onPlaced(purchase);
    }
  }
}

void main() {
  final checkout = Checkout()
    ..addListener(ConfirmationMail(mailer))
    ..addListener(StockUpdate(warehouse));
}

Plain Dart, a stream. A StreamController replaces the list. Listeners subscribe and must cancel their subscription.

class Checkout {
  final _placed = StreamController<Purchase>.broadcast();

  Stream<Purchase> get placed => _placed.stream;

  void place(Purchase purchase) {
    // ... save the purchase
    _placed.add(purchase);
  }

  Future<void> close() => _placed.close();
}

final subscription = checkout.placed.listen(
  (purchase) => mailer.send(purchase.email, 'Thank you'),
);

Spring for Dart, an injected list. A List<PurchaseListener> parameter receives every bean that implements the interface, sorted by @Order.

@Service()
class Checkout {
  Checkout(this.listeners);

  final List<PurchaseListener> listeners;

  void place(Purchase purchase) {
    // ... save the purchase
    for (final listener in listeners) {
      listener.onPlaced(purchase);
    }
  }
}

@Component()
@Order(1)
class StockUpdate implements PurchaseListener {
  StockUpdate(this.warehouse);
  final Warehouse warehouse;

  @override
  void onPlaced(Purchase purchase) => warehouse.reserve(purchase.id);
}

What changes: nobody calls addListener. The container builds each listener with its own dependencies and hands the whole list to Checkout. There is no subscription to cancel, because listeners live as long as the application.

Adding a new listener

Plain Dart. Two edits: the new class, and the place where listeners are wired.

class LoyaltyPoints implements PurchaseListener {
  LoyaltyPoints(this.accounts);
  final Accounts accounts;

  @override
  void onPlaced(Purchase purchase) => accounts.addPoints(purchase.email, purchase.total ~/ 10);
}

// and in main, or wherever Checkout is built:
checkout.addListener(LoyaltyPoints(accounts));

Spring for Dart. One edit: the new class.

@Component()
class LoyaltyPoints implements PurchaseListener {
  LoyaltyPoints(this.accounts);
  final Accounts accounts;

  @override
  void onPlaced(Purchase purchase) => accounts.addPoints(purchase.email, purchase.total ~/ 10);
}

What changes: Checkout, main and the other listeners are not touched. A listener that is only wanted in one environment adds @Profile(['prod']), and a test can leave it out the same way. The cost: the wiring is no longer visible in one place; to see who listens, you look for the implementations of PurchaseListener.

Events without a shared interface

Sometimes the listeners should not even share an interface with the publisher: different modules react to different events, each in its own way.

Plain Dart. A shared event bus, usually a broadcast stream of Object, filtered by type.

final bus = StreamController<Object>.broadcast();

// publisher
bus.add(PurchasePlaced(purchase));

// listeners, wherever they are created
bus.stream.listen((event) {
  if (event is PurchasePlaced) mail(event);
});
bus.stream.listen((event) {
  if (event is PurchasePlaced && event.purchase.total > 1000) alertSales(event);
});

Spring for Dart. Inject ApplicationEventPublisher and publish any object. Any bean method with @EventListener() and a parameter of that type receives it.

class PurchasePlaced {
  const PurchasePlaced(this.purchase);
  final Purchase purchase;
}

bool isLarge(PurchasePlaced event) => event.purchase.total > 1000;

@Service()
class Checkout {
  Checkout(this.events);
  final ApplicationEventPublisher events;

  void place(Purchase purchase) {
    // ... save the purchase
    events.publishEvent(PurchasePlaced(purchase));
  }
}

@Component()
class SalesTeam {
  SalesTeam(this.mailer);
  final Mailer mailer;

  @EventListener(condition: isLarge) // only purchases over 1000
  @Order(1)                          // before listeners with a higher order
  void onLarge(PurchasePlaced event) => mailer.send('[email protected]', event.purchase.id);

  @EventListener()
  @Async()                           // publishEvent does not wait for it
  Future<void> onAny(PurchasePlaced event) => mailer.send(event.purchase.email, 'Thank you');
}

What changes: the bus is the application context itself, so there is no global stream to create, pass around or close. The condition is a top-level function checked by type. @Async() takes effect only when the context has a TaskExecutor bean (spring_boot_starter_scheduling registers one); without it the listener runs inside publishEvent. The same @EventListener also receives the context's own events, such as ContextRefreshedEvent.

Which Spring form to pick: the injected list when the publisher should know that listeners exist and call them in order (and wait for them); events when the publisher should know nothing about who reacts.

In short

Listener list StreamController Spring List<PurchaseListener> Spring events
Who wires the listeners your code, addListener each listener subscribes the container the container
A new listener a class and a registration a class and a listen call a class a method with @EventListener()
Order registration order not defined @Order @Order on the method
Filter in the listener where on the stream in the listener condition:
Asynchronous by hand yes, always by hand @Async() with a TaskExecutor
Clean-up removeListener cancel the subscription, close the controller none none
Build step none none build_runner build_runner

Streams remain the right tool for data that changes over time inside one widget or one class, such as a value a UI listens to. The Spring forms are for application-wide reactions, where the list of listeners grows as features are added.

See also