Junior — Middle
Explain the concept of data streams in programming and their application.
sobes.tech AI
Answer from AI
Data streams in programming are sequences of data that arrive asynchronously over time. They allow processing of events or data as they occur, without blocking the main execution thread.
In Flutter, data streams are often used for handling asynchronous events such as user input, fetching data from the network, or updating state.
Example of using Stream in Dart:
Stream<int> countStream(int max) async* {
for (int i = 1; i <= max; i++) {
await Future.delayed(Duration(seconds: 1));
yield i; // send a new value to the stream
}
}
void main() {
var stream = countStream(3);
stream.listen((value) {
print('Received value: $value');
});
}
Here, a new number is sent to the stream every second, and the listener receives these values as they appear. This approach is convenient for reactive programming and real-time event handling.