publishReplay method

ReplayConnectableStream<T> publishReplay({
  1. int? maxSize,
})

Convert the current Stream into a ReplayConnectableStream that can be listened to multiple times. It will not begin emitting items from the original Stream until the connect method is invoked.

This is useful for converting a single-subscription stream into a broadcast Stream that replays a given number of items to any new listener. It also provides access to the emitted values synchronously.

Example

final source = Stream.fromIterable([1, 2, 3]);
final connectable = source.publishReplay();

// Does not print anything at first
connectable.listen(print);

// Start listening to the source Stream. Will cause the previous
// line to start printing 1, 2, 3
final subscription = connectable.connect();

// Late subscribers will receive the emitted value, up to a specified
// maxSize
connectable.listen(print); // Prints 1, 2, 3
await Future(() {});

// Can access a list of the emitted values synchronously. Prints [1, 2, 3]
print(connectable.values);

// Stop emitting items from the source stream and close the underlying
// ReplaySubject
subscription.cancel();

Implementation

ReplayConnectableStream<T> publishReplay({int? maxSize}) =>
    ReplayConnectableStream<T>(this, maxSize: maxSize, sync: true);