Gazihan Alankus
Gazihan Alankus

Reputation: 11984

Dart streams, equivalent of await for

I like the await for construct in Dart.

How can I implement something similar with a regular for loop?

Something like

// beware! fictional code.
var element = stream.next();
for(; stream.isEndReached(); element = stream.next()) {
  // use element here
}

// or probably it will be like this, right? 
var element = await stream.next();
for(; await stream.isEndReached(); element = await stream.next()) {
  // use element here
}

But I can't figure out what functions to use instead of next() and isEndReached() here. If you could give me a full example that acts exactly like async for, that would be great.

Edit: Here is the actual reason that I asked for this: I want to do something like this:

if (!stream.isEndReached()) {
  var a = await stream.next();
  // use a
}

if (!stream.isEndReached()) {
  var b = await stream.next();
  // use b
}

// have an arbitrary number of these

I need to consume items one by one like this. This is why I'm asking what my made up .next() and .isEndReached() methods map to which actual methods in the stream class.

Upvotes: 3

Views: 3858

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657208

The async package contains a StreamQueue class that might do what you want.

See also this great article http://news.dartlang.org/2016/04/unboxing-packages-async-part-3.html

StreamQueue provides a pull-based API for streams.

A code snipped from the article mentioned above

void main() async {
  var queue = new StreamQueue(new Stream.fromIterable([1, 2, 3]));
  var first = queue.next;
  var second = queue.next;
  var third = queue.next;
  print(await Future.wait([first, second, third])); // => [1, 2, 3]
}

update

WebStorm (uses a feature of the dartanalyzer) doesn't provide quick fixes for imports when nothing was yet imported from that package. It doesn't read packages if they are not refered to in your source code. As mentioned in my answer StreamQueue is from the async package. import 'package:async/async.dart'; is usually enough (it's a convention to name the main entrypoint file (async.dart) of a package the same as the package) and all exported identifiers become available in your library. Otherwise you can search the source of your project and WebStorm will also search dependencies and show what library contains the StreamQueue class. Then you can import this file.

Upvotes: 8

Related Questions