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?
A more imporant difference is that
await for
serializes the consumption of the stream items whilelisten
will process them concurrently.For example the code below:
yields
The main difference is when there's code afterwards.
listen
only register the handler and the execution continue.await for
will retain execution until the stream is closed.Thus if you add a
print('hello');
at the end of yourmain
you shouldn't see hello in the output withawait for
(because the request stream is never closed). Try the following code on dartpad to see the differences :Given:
then:
yields:
whereas:
yields:
stream.listen()
sets up code that will be put on the event queue when an event arrives, then following code is executed.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).
Check https://www.dartlang.org/articles/language/beyond-async for a description of
await for
.