Junior — Middle
Explain the concept of streams in Dart and their main features.
sobes.tech AI
Answer from AI
In Dart, a Stream is a sequence of asynchronous events that can arrive over time. Streams allow working with data that comes not immediately, but gradually, such as network data, user events, or timers.
Main features of Stream:
- Asynchronous: events can arrive at different times, processing occurs without blocking the main thread.
- Subscription: to receive events, you need to subscribe to the stream.
- Stream types: single-subscription and broadcast.
- Event handling: you can use
listen,await for, and stream transformations (map, where, etc.).
Example:
Stream<int> countStream(int max) async* {
for (int i = 1; i <= max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i; // send event
}
}
void main() async {
await for (var value in countStream(3)) {
print(value); // will print 1, then 2, then 3 with 1 second delay
}
}
Thus, Stream is a powerful tool for working with asynchronous data in Flutter and Dart.