The difference between waiting and listening in Dart

I am trying to create a web server thread. 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 listening and waiting? They both do not work at the same time. You need to comment one or the other in order to work, but there is no difference in function here. Are there circumstances when there is a difference, and when you should use one over the other?

+5
source share
2 answers

Given:

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

then

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

gives:

 BEFORE AFTER mene mene tekel parsin 

then:

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

gives:

 BEFORE mene mene tekel parsin AFTER 

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

await for pauses between events and continues to do so until the thread is executed, so subsequent code will not be executed until this happens.

I use wait when I have a thread that I know will have final events and I need to process them before doing anything else (essentially as if I were dealing with a list of futures).

Check out the https://www.dartlang.org/articles/language/beyond-async await for description.

+8
source

The main difference is when the code is later. listen registers only the handler and execution continues. await for keep executing until the thread is closed.

Thus, if you add print('hello'); at the end of your main , you will not see an output greeting using await for (because the request stream never closes). Try the following code on dartpad to see the differences:

 import 'dart:async'; main() async { tenInts.listen((i) => print('int $i')); //await for (final i in tenInts) { // print('int $i'); //} print('hello'); } Stream<int> get tenInts async* { for (int i = 1; i <= 10; i++) yield i; } 
+5
source

Source: https://habr.com/ru/post/1265063/


All Articles