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. :)
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));
}
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With