Junior — Middle
What is the main task and application of data streams in the Dart language?
sobes.tech AI
Answer from AI
Streams in Dart are used for working with asynchronous data sequences that arrive over time. The main purpose of streams is to allow processing data as it arrives without blocking the main execution thread.
The applications of streams in Dart include:
- Handling user interface events.
- Receiving data from the network or files in parts.
- Implementing reactive programming.
Example of using a stream:
Stream<int> countStream(int to) async* {
for (int i = 1; i <= to; i++) {
await Future.delayed(Duration(seconds: 1));
yield i; // send value to the stream
}
}
void main() {
countStream(3).listen((value) {
print('Received value: $value');
});
}
Here, the stream outputs numbers sequentially with a delay, and we can react to each value as it appears.