StreamController Extension

Hi,
I found the following methods are quite useful to control stream.
Currently, I create an extension on StreamController, is it possible to add these methods in StreamController?

  void mayAdd(T event) {
    if (!isClosed && hasListener) {
      add(event);
    }
  }

  void mayAddError(Object error, [StackTrace? stackTrace]){
    if (!isClosed && hasListener) {
      addError(error, stackTrace);
    }
  }

  Future<void> mayClose() async {
    if (!isClosed && !hasListener) {
      await close();
    }
  }

1 possible answer(s) on “StreamController Extension

  1. If the onCancel is on the stream of controller, then I can absolutely gurantee that controller.hasListener will be false when onCancel is called, both for single-subscription and broadcast streams. Not having a listener is what triggers onCancel being called.
    What you do is equivalent to await controller?.close(). It’s safe to call close twice, so there is no need to check isClosed first.

    If it is not a broadcast stream, it’s unnecessary to close the controller. The one and only listener has already stopped listening, so noone will get the done event.

    For the remaining uses, I think they derive from the way you are using controllers, but they are not general enough that we’d want to have them on the controller for everybody.