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?
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.
There are two types of streams in Flutter: single subscription streams and broadcast streams. Single subscription streams are the default.
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.
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.
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.
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