在Dart中等待和聆听之间的区别 [英] Difference between await for and listen in Dart

查看:195
本文介绍了在Dart中等待和聆听之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建Web服务器流.这是代码:

I am trying to create a web server stream. Here is the code:

import 'dart:io';

main() async {
  HttpServer requestServer = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8000);

requestServer.listen((request) {   //comment out this or the await for to work
  request.response
    ..write("This is a listen stream")
    ..close();
});

  await for (HttpRequest request in requestServer) {
  request.response
    ..write("This is an await for stream")
    ..close();
  }
}

监听和等待之间有什么区别?它们两者不能同时工作.您需要注释掉其中一个才能工作,但是这里的功能似乎没有什么区别.在某些情况下会有区别吗?何时应该使用另一种?

What is the difference between listen and await for? They both do not work at the same time. You need to comment out one or the other to work, but there doesn't seem to be a difference in function here. Are there circumstances where there is a difference, and when should you use one over the other?

推荐答案

给出:

Stream<String> stream = new Stream<String>.fromIterable(['mene', 'mene', 'tekel', 'parsin']);

然后:

print('BEFORE');
stream.listen((s) { print(s); });
print('AFTER');

产量:

BEFORE
AFTER
mene
mene
tekel
parsin

而:

print('BEFORE');
await for(String s in stream) { print(s); }
print('AFTER');

产量:

BEFORE
mene
mene
tekel
parsin
AFTER

stream.listen()设置将在事件到达时放入事件队列中的代码,然后执行以下代码.

stream.listen() sets up code that will be put on the event queue when an event arrives, then following code is executed.

await for会在事件之间挂起,并一直这样做直到流完成,因此,直到发生这种情况之后,才会执行其后的代码.

await for suspends between events and keeps doing so until the stream is done, so code following it will not be executed until that happens.

当有已知的有限事件流时,我使用等待",并且在进行其他任何操作之前(基本上就像在处理期货列表一样),我需要对其进行处理.

I use `await for when I have a stream that I know will have finite events, and I need to process them before doing anything else (essentially as if I'm dealing with a list of futures).

检查 https://www.dartlang.org/articles/language/beyond-async 获取await for的描述.

这篇关于在Dart中等待和聆听之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆