stream property

Stream<SyncProgress> get stream

Subscribes to the stream of SyncProgress events. New subscribers always receive the latest event first (replay-1), then any future events.

Implementation

Stream<SyncProgress> get stream {
  // We use a transformer-style approach:
  // the returned stream is a single-subscription
  // stream that yields the latest first, then
  // listens to the broadcast controller.
  late StreamController<SyncProgress> wrapper;
  StreamSubscription<SyncProgress>? sub;
  StreamSubscription<SyncProgress>? replaySub;
  final Completer<void> replayDone = Completer<void>();
  wrapper = StreamController<SyncProgress>(
    onListen: () {
      // Replay the latest synchronously.
      wrapper.add(_latest);
      // Then subscribe to the broadcast.
      sub = _controller.stream.listen(wrapper.add,
          onError: wrapper.addError, onDone: wrapper.close);
      // Close the wrapper when the controller closes.
      replaySub = _controller.stream.listen(
        (_) {},
        onDone: () {
          if (!replayDone.isCompleted) replayDone.complete();
        },
      );
    },
    onCancel: () async {
      await sub?.cancel();
      await replaySub?.cancel();
    },
  );
  return wrapper.stream;
}