Previously added Stream value to return on listen (Broadcast Stream)

Viewed 958

I have a custom StreamController<int>:

final StreamController listener = StreamController<int>.broadcast();

After initialization, I emit a value to the stream

listener.add(7);

After emitting the value, I set a Stream listener

listener.stream.listen((val) {
    print(val);
});

The expected behavior is that the listener will return the previously set value, however, that's not the case. Only if I set the value after I set the listener, the listener will be called.

How can I achieve that behavior?

(Edit: Multiple listeners have to be supported)

2 Answers

First, don't make the Stream a broadcast stream since the definition of this kind of stream is to allow multiple subscribers but all events will be lost if there are no current subscribers.

Afterwards, take a look at the asBroadcastStream on the Stream returned from the StreamController. This method allows implementing logic where the Stream are first listened on after the first subscriber and also makes it possible to make logic like pause the stream if there are no more subscribers.

You can utilize StreamController onListen callback for it since it's gonna be called every time somebody subscribes.

class StreamExample {
  late final StreamController<dynamic> _controller;
  dynamic _val;

  StreamExample() {
    _controller = StreamController.broadcast();
    _controller.onListen = () => _controller.add(_val);
  }

  /// Example setter for value which works 
  /// like [ChangeNotifier] for [Stream] listeners.
  void set val(value) {
    _val = value;
    _controller.add(value);
  }

  Stream<dynamic> get stream => _controller.stream;
}
Related