简体   繁体   English

Dart流中listen和forEach有什么区别?

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

If I have Stream in Dart, I can use both listen and forEach , but I don't understand the difference. 如果我有Dart Stream ,我可以同时使用listenforEach ,但我不明白其中的区别。

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? 有什么区别吗?

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. Stream上的forEach函数将在第一个错误处停止,并且它不会为您提供StreamSubscription来控制您在流上的监听方式。 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. 使用forEach非常棒,如果这就是你想要的 - 它告诉你什么时候完成(返回的Future ),你所要做的就是处理事件。 If you need more control, you can use the listen call which is how forEach is implemented. 如果您需要更多控制,可以使用listen调用,这就是如何实现forEach

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. 这就像Iterable.forEachIterable.iterator之间的区别 - 前者只是为每个元素调用一个回调,另一个为您提供了一种控制迭代的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM