Search code examples
dartdart-async

What is the best/shortest way to convert an Iterable to a Stream, in Dart?


I have an Iterable, and I'd like to convert it to a Stream. What is the most efficient/shortest-amount-of-code to do this?

For example:

Future convert(thing) {
  return someAsyncOperation(thing);
}

Stream doStuff(Iterable things) {
  return things
    .map((t) async => await convert(t)) // this isn't exactly what I want
                                        // because this returns the Future
                                        // and not the value
    .where((value) => value != null)
    .toStream(); // this doesn't exist...
}

Note: iterable.toStream() doesn't exist, but I want something like that. :)


Solution

  • Here's a simple example:

    var data = [1,2,3,4,5]; // some sample data
    var stream = new Stream.fromIterable(data);
    

    Using your code:

    Future convert(thing) {
      return someAsyncOperation(thing);
    }
    
    Stream doStuff(Iterable things) {
      return new Stream.fromIterable(things
        .map((t) async => await convert(t))
        .where((value) => value != null));
    }