listen method

CancelListenFunc listen(
  1. FutureOr<void> onEvent(
    1. T
    )
)

Implementation

CancelListenFunc listen(FutureOr<void> Function(T) onEvent) {
  //
  FutureOr<void> Function(T) func = onEvent;
  if (synchronized) {
    // ensure `onEvent` will trigger one by one (waits for previous `onEvent` to complete)
    func = (event) async {
      await _syncLock.synchronized(() async {
        await onEvent(event);
      });
    };
  }

  final listener = emitter.streamCtrl.stream.listen(func);
  _listeners.add(listener);

  // make a cancel func to cancel listening and remove from list in 1 call
  cancelFunc() async {
    await listener.cancel();
    _listeners.remove(listener);
    logger.fine('${objectId} event was cancelled by func');
  }

  return cancelFunc;
}