Handling Streams
- Streams
- Handling Streams
Use async and an asynchronous for loop (await for).
Use the Stream API, as described in the library tour .
Wait until the stream emits a value.
Execute the body of the for loop, with the variable set to that emitted value.
Repeat 1 and 2 until the stream is closed.
A stream is a sequence of asynchronous events. It is like an asynchronous Iterable—where, instead of getting the next event when you ask for it, the stream tells you that there is an event when it is ready.
When you need to get values from a Stream, you have two options:
Note:
Before using await for, be sure that it makes the code clearer and that you really do want to wait for all of the stream’s results. For example, you usually should not use await for for UI event listeners, because UI frameworks send endless streams of events.
An asynchronous for loop has the following form:
await for (varOrType identifier in expression) {
// Executes each time the stream emits a value.
}
The value of expression must have type Stream. Execution proceeds as follows:
To stop listening to the stream, you can use a break or return statement, which breaks out of the for loop and unsubscribes from the stream.
If you get a compile-time error when implementing an asynchronous for loop, make sure the await for is in an async function. For example, to use an asynchronous for loop in your app’s main() function, the body of main() must be marked as async:
Future main() async {
// ...
await for (var request in requestServer) {
handleRequest(request);
}
// ...
}
If you went to go deeper into this subject : Streams