onEvent<T extends Event> method

Stream<T> onEvent<T extends Event>([
  1. String? type
])

Attach a listener to an emitter. Calls the callback whenever there's a new event of the specified type and data type.

This method can be used with generalized types, such as Object/dynamic and other super classes.

It can be canceled using the StreamSubscription from the .listen( ... ).

  StreamEventEmitter events = StreamEventEmitter();
    ...
  final subscription = events.on<Event<String>>('message').listen((Event<String> event) => print('String: ${event.type} ${event.data}'));
    ...
  subscription.cancel();

This method can also be used to catch custom events, which extend the Event class.

Implementation

Stream<T> onEvent<T extends Event>([String? type]) {
  var stream = controller.stream;
  if (type != null) stream = stream.where((event) => event.type == type);
  return stream.whereType<T>();
}