Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between await for and listen in Dart

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?

like image 569
richalot Avatar asked Mar 05 '17 17:03

richalot


People also ask

What does await do in Dart?

When you await an asynchronous function, the execution of the code within the caller suspends while the async operation is executed. When the operation is completed, the value of what was awaited is contained within a Future object.

What's the difference between async and async * in Dart?

What is the difference between async and async* in Dart? The difference between both is that async* will always return a Stream and offer some syntax sugar to emit a value through the yield keyword. async gives you a Future and async* gives you a Stream.

What are different types of streams in flutter?

There are two types of streams in Flutter: single subscription streams and broadcast streams. Single subscription streams are the default.

What is listen in flutter?

Listener class Null safety. A widget that calls callbacks in response to common pointer events. It listens to events that can construct gestures, such as when the pointer is pressed, moved, then released or canceled.


1 Answers

Given:

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

then:

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

yields:

BEFORE AFTER mene mene tekel parsin 

whereas:

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

yields:

BEFORE mene mene tekel parsin AFTER 

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.

like image 161
Argenti Apparatus Avatar answered Sep 20 '22 09:09

Argenti Apparatus