toSafeStream method

Stream<Result<T>> toSafeStream({
  1. required bool cancelOnError,
})

Transforms a Stream<T> into a Stream<Result<T>>.

Each data event from the original stream is wrapped in an Ok<T>. Each error event is wrapped in an Err<T>.

If cancelOnError is true, the stream will be closed upon the first error.

Implementation

Stream<Result<T>> toSafeStream({required bool cancelOnError}) {
  return transform(
    StreamTransformer.fromHandlers(
      handleData: (data, sink) {
        sink.add(Ok(data));
      },
      handleError: (error, stackTrace, sink) {
        if (error is Err) {
          sink.add(error.transfErr());
        } else {
          sink.add(Err<T>(error));
        }
        if (cancelOnError) {
          sink.close();
        }
      },
      handleDone: (sink) {
        sink.close();
      },
    ),
  );
}