newStreamWithInitialValue method

Stream<T> newStreamWithInitialValue(
  1. T initialValue
)

This stream with initialValue emitted first, to every listener. Broadcast-ness is preserved; the source is only subscribed while the returned stream has listeners.

Implementation

Stream<T> newStreamWithInitialValue(T initialValue) {
  late final StreamController<T> controller;
  StreamSubscription<T>? subscription;
  var listeners = 0;

  void onListen() {
    controller.add(initialValue);
    if (listeners++ == 0) {
      subscription = listen(controller.add, onError: controller.addError, onDone: controller.close);
    }
  }

  void onCancel() {
    if (--listeners == 0) {
      subscription?.cancel();
      controller.close();
    }
  }

  controller = isBroadcast
      ? StreamController<T>.broadcast(onListen: onListen, onCancel: onCancel)
      : StreamController<T>(
          onListen: onListen,
          onPause: () => subscription?.pause(),
          onResume: () => subscription?.resume(),
          onCancel: onCancel,
        );
  return controller.stream;
}