Junior — Middle
Can you explain what a Stream Controller is in Dart and what it is used for?
sobes.tech AI
Answer from AI
StreamController in Dart is a class that allows creating and managing data streams (Streams). It acts as an intermediary that can receive events (data, errors, completion) and broadcast them to stream listeners (subscribers).
The main purpose of StreamController is to create a stream into which events can be manually added, and other parts of the program can subscribe to this stream and react to incoming data.
Example of usage:
import 'dart:async';
void main() {
final controller = StreamController<int>();
// Subscribe to the stream
controller.stream.listen((data) {
print('Received: $data');
});
// Add data to the stream
controller.add(1);
controller.add(2);
// Close the controller
controller.close();
}
Thus, StreamController is useful for creating custom event streams, managing them, and passing data between asynchronous parts of an application.