publishEvent abstract method

Future<void> publishEvent(
  1. ApplicationEvent event
)

Publishes the given event to all registered ApplicationEventListeners.

This method implements the Observer pattern within the application context, allowing decoupled communication between application components.

Event Delivery Guarantees:

  • Synchronous Delivery: Events are typically delivered synchronously
  • Order Preservation: Events are delivered in publication order
  • Exception Handling: Listener exceptions are caught and logged
  • Thread Context: Events are published in the caller's thread context

Event Types:

  • Context Lifecycle Events: ContextRefreshedEvent, ContextClosedEvent
  • Application Domain Events: UserCreatedEvent, OrderProcessedEvent
  • Framework Events: Internal framework operation events

Example:

class OrderService {
  final ApplicationContext context;
  
  OrderService(this.context);
  
  Future<Order> createOrder(OrderRequest request) async {
    final order = Order.fromRequest(request);
    
    // Persist order
    await orderRepository.save(order);
    
    // Publish domain event
    context.publishEvent(OrderCreatedEvent(this, order));
    
    return order;
  }
}

class OrderEventListener implements ApplicationEventListener<OrderCreatedEvent> {
  @override
  void onApplicationEvent(OrderCreatedEvent event) {
    // Send confirmation email
    emailService.sendConfirmation(event.order);
    
    // Update inventory
    inventoryService.reserveItems(event.order.items);
  }
}

Error Handling:

If a listener throws an exception, it is caught and logged, but other listeners will still receive the event. The publishing code is not affected by listener exceptions.

Implementation

Future<void> publishEvent(ApplicationEvent event);