stream method

Stream<JSObject> stream(
  1. JSObject input
)

Sends one request once listened to, after every request submitted before it, and streams the chunks the worker emits for it. Cancelling asks the worker to stop, at once where its script handles a cancel and otherwise after the chunk in progress, and waits for it. A failure arrives as a TaskException and closes the stream.

Implementation

Stream<JSObject> stream(JSObject input) {
  late StreamController<JSObject> chunks;
  _WorkerStream? request;
  Future<void>? finished;
  chunks = StreamController<JSObject>(
    onListen: () {
      if (_closed) {
        chunks.addError(StateError('The task has been disposed.'));
        unawaited(chunks.close());
        return;
      }
      final started = _stream(_id, input, chunks.add.toJS);
      request = started;
      finished = _reported(started.done)
          .then<void>((_) {}, onError: chunks.addError)
          // Not waiting for the close, which waits for onCancel, which a
          // finished stream also calls, and which waits for this.
          .whenComplete(() => unawaited(chunks.close()));
    },
    onCancel: () {
      request?.cancel();
      return finished;
    },
  );
  return chunks.stream;
}