broadcast method

Future<void> broadcast(
  1. NyEvent event, [
  2. Map? data
])

Implementation

Future<void> broadcast(NyEvent event, [Map? data]) async {
  final Type eventType = event.runtimeType;

  if (_subscriptions.containsKey(eventType)) {
    final listeners = List<NyListener>.from(_subscriptions[eventType]!);

    // Invoke onBroadcast callback if set
    onBroadcast?.call(event, listeners.length);

    for (var listener in listeners) {
      // Skip if listener was already removed (could happen if returning false in a callback)
      if (!_subscriptions.containsKey(eventType) ||
          !_subscriptions[eventType]!.contains(listener)) {
        continue;
      }

      try {
        listener.setEvent(event);
        dynamic result = await listener.handle(data);

        // Check if we should stop propagation
        if (result != null && result == false) {
          break;
        }
      } catch (e, stackTrace) {
        // Log or handle error without breaking the chain
        if (onError != null) {
          onError!(e, stackTrace);
        } else if (debugMode) {
          // ignore: avoid_print
          print(
            'NyEventBus Error in listener for $eventType: $e\n$stackTrace',
          );
        }
      }
    }
  }
}