withLatestValue method

Stream<T> withLatestValue()

Returns a stream that replays the latest emitted value to new subscribers.

This is similar in behavior to a “behavior subject” – whenever a new listener subscribes, it immediately receives the most recent value.

Example:

myStream.withLatestValue().listen((data) => print('Listener got: $data'));

Implementation

Stream<T> withLatestValue() {
  T? latestValue;
  var hasValue = false;
  final source = asBroadcastStream();

  return Stream<T>.multi((multiController) {
    if (hasValue) {
      multiController.add(latestValue as T);
    }
    final subscription = source.listen(
      (data) {
        latestValue = data;
        hasValue = true;
        multiController.add(data);
      },
      onError: multiController.addError,
      onDone: multiController.close,
    );
    multiController.onCancel = () => subscription.cancel();
  });
}