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

I have Iterable and would like to convert it to Stream. What is the most efficient / shortest amount of code for 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 () does not exist, but I want something like this. :)

+7
dart dart-async
source share
3 answers

Here is 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)); } 
+6
source share

If you are using the Dart SDK version 1.9 or later, you can 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); } 

It may be easier to read because it has fewer braces and “special” methods, but it is a matter of taste.

+3
source share

If you want to process each element sequentially in 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)) } 
+1
source share

All Articles