Junior — Middle
What methods can be used to implement a data stream in Dart?
sobes.tech AI
Answer from AI
In Dart, there are several approaches to implementing data streams (streams):
- Stream and StreamController — the primary way to work with streams.
StreamControllerallows creating a stream to which events can be added, andStreamis the stream itself that you can subscribe to.
final controller = StreamController<int>();
controller.stream.listen((data) {
print('Received: $data');
});
controller.add(1);
controller.add(2);
controller.close();
- Asynchronous generators (async)* — allow creating a data stream using a function that returns a
Streamand uses theyieldkeyword to emit values.
Stream<int> countStream(int to) async* {
for (int i = 1; i <= to; i++) {
yield i;
await Future.delayed(Duration(seconds: 1));
}
}
countStream(3).listen(print);
- Using ready-made streams from libraries — for example,
Stream.periodicfor periodic events.
Thus, the main methods are using StreamController for creating and managing streams and asynchronous generators for conveniently creating streams with data generation logic.