subscribe<TEvent extends IEvent> method

EventSubscription subscribe<TEvent extends IEvent>(
  1. EventFuction<TEvent> callback
)

Subscribes a callback to be executed when the TEvent is raised.

mediator.subscribe((TEvent event) async => doStuff(event));

Events are raised with the raise function on the Mediator.

Implementation

EventSubscription subscribe<TEvent extends IEvent>(
  EventFuction<TEvent> callback,
) {
  List<WeakEventFunction>? subscribers = _eventSubscribers[TEvent];
  if (subscribers == null) {
    subscribers = [];
    _eventSubscribers[TEvent] = subscribers;
  } else {
    // This only cleans up the GC'd subscribers for the current event but I think that's okay.
    List<WeakEventFunction> toRemove = [];
    for (WeakEventFunction ref in subscribers) {
      if (ref.target == null) toRemove.add(ref);
    }

    toRemove.forEach(subscribers.remove);
  }

  WeakEventFunction ref = WeakEventFunction(callback);
  subscribers.add(ref);

  return EventSubscription._(TEvent, ref);
}