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

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


Here's a simple example:

var data = [1,2,3,4,5]; // some sample datavar 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));}


In case you are using the Dart SDK version 1.9 or a newer one, you could easily create a stream using async*

import 'dart:async';Future convert(thing) {  return new Future.value(thing);}Stream doStuff(Iterable things) async* {  for (var t in things) {    var r = await convert(t);    if (r != null) {      yield r;    }  }}void main() {  doStuff([1, 2, 3, null, 4, 5]).listen(print);}

Maybe it is easier to read as it has less braces and "special" methods, but that is a matter of taste.


If you want to sequentially process each item in the iterable you can use Stream.asyncMap:

Future convert(thing) {  return waitForIt(thing);   // async operation}f() {  var data = [1,2,3,4,5];  new Stream.fromIterable(data)    .asyncMap(convert)    .where((value) => value != null))}