Flutter StreamGroup

Jitesh Mohite
FlutterWorld
Published in
2 min readJul 4, 2020

--

StreamGroup is a class which contains n number of stream and execute simultaneously. This is managed by a central stream of StreamGroup.

How we can add multiple Streams?

The streams are provided in the form of a list & given to StreamGroup to work parallelly.

final result = StreamGroup.merge([
stream1,
stream2,
stream3
]);

How to listen to streams:

The below code shows that you are listening to a single-stream group which is here in the result variable. This will provide you callback of all streams in one single stream.

Both errors and data events are forwarded through the stream. The streams in the group won’t be listened to until stream has a listener.

The stream provides a single subscription, which means if stream gets paused than all streams under it will also get paused or canceled.

stream won’t close until close is called on the group and every stream in the group closes.

void main() {
Stream<String> stream1 = new Stream.fromFuture(getData(2));
Stream<String> stream2 = new Stream.fromFuture(getData(4));
Stream<String> stream3 = new Stream.fromFuture(getData(6));
final result = StreamGroup.merge([
stream1,
stream2,
stream3
]);
result.listen((data) {
print("DataReceived: " + data);
});
}

getData() is Future Task which will run after certain Duration.

Future<String> getData(int duration) async {
await Future.delayed(Duration(seconds: duration)); //Mock delay
return "This a test data";
}

Output:

I/flutter ( 5866): DataReceived: This a test data — Print after 2 seconds
I/flutter ( 5866): DataReceived: This a test data — Print after 4 seconds
I/flutter ( 5866): DataReceived: This a test data — Print after 6 seconds

--

--

Jitesh Mohite
FlutterWorld

I am technology enthusiastic, want to learn things quickly and dive deep inside it. I always believe in developing logical things which makes impact on end user