skip to Main Content

Lets say there is a Stream<Foo> that can throw exceptions but we need to convert it to Stream<Result<Foo>> and instead of throwing, returning a Result<Foo> with the exception.
How can it be done?

For clarity that’s what the Result class looks like:

sealed class Result<T> {
  Result();

  factory Result.success(T data) = ResultSuccess<T>;

  factory Result.error(String message) = ResultError<T>;
}

final class ResultSuccess<T> extends Result<T> {
  final T data;

  ResultSuccess(this.data);
}

final class ResultError<T> extends Result<T> {
  final String message;

  ResultError(this.message);
}

2

Answers


  1. Chosen as BEST ANSWER

    We can use StreamTransformer.fromHandlers.

    StreamTransformer<Foo>, Result<Foo>.fromHandlers(
      handleError: (error, stackTrace, sink) {
        sink.add(Result.error('Error: $error'));
      },
      handleData: (data, sink) {
        sink.add(Result.success(data));
      },
    )
    

    and then use it with our initial stream:

    final transformer = StreamTransformer<Foo>, Result<Foo>.fromHandlers(
      handleError: (error, stackTrace, sink) {
        sink.add(Result.error('Error: $error'));
      },
      handleData: (data, sink) {
        sink.add(Result.success(data));
      },
    )
    final resultStream = initialStream.transform(transformer);
    

  2. You might also consider writing an "asResult" operator as an extension method which would enable you to then write something like…

    myStream.asResult().listen(...
    

    Pseudocodish implementation follows …

    extension ResultOperator<T> on Stream<T> {
      Stream<Result<T?>> asResult() {
        final controller = StreamController<Result<T?>>();
        final subscription = listen( ...
    
        // ... handle error/value/done etc, and add your Results via
        // the sink, before returning the stream.
         
    
      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search