Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between listen and forEach in Dart streams?

Tags:

stream

dart

If I have Stream in Dart, I can use both listen and forEach, but I don't understand the difference.

So for example consider this code:

final process = await Process.start('pub', ['serve']);
process.stdout.map((l) => UTF8.decode(l)).forEach(print);

I could also have written:

process.stdout.map((l) => UTF8.decode(l)).listen(print);

Is there any difference?

like image 770
Kasper Avatar asked Jan 09 '16 21:01

Kasper


People also ask

How do I listen to stream darts?

Listening to streams You can use the listen() method to subscribe to the stream. The only required parameter is a function. Simple code for creating and listening to a stream. That's how listen() works.

What are different types of streams in flutter?

There are two types of streams in Flutter: single subscription streams and broadcast streams. Single subscription streams are the default.

What are streams in Dart?

Streams provide an asynchronous sequence of data. Data sequences include user-generated events and data read from files. You can process a stream using either await for or listen() from the Stream API. Streams provide a way to respond to errors. There are two kinds of streams: single subscription or broadcast.

What is stream and event in flutter?

A Stream provides a way to receive a sequence of events. Each event is either a data event, also called an element of the stream, or an error event, which is a notification that something has failed.


1 Answers

The forEach function on a Stream will stop at the first error, and it won't give you a StreamSubscription to control how you listen on a stream. Using forEach is great if that's what you want - it tells you when it's done (the returned Future) and all you have to do is handle the events. If you need more control, you can use the listen call which is how forEach is implemented.

It's like the difference between Iterable.forEach and Iterable.iterator - the former just calls a callback for each element, the other gives you a way to control the iteration.

like image 105
lrn Avatar answered Sep 30 '22 14:09

lrn