Flutter: How to use multiple streams combine

Viewed 2326

The question says it clearly, how to perform/combine multiple streams at the same time.

Let suppose we have a stream like

main() {
  print("Creating a sample stream...");
  Stream<String> stream = new Stream.fromFuture(getData());
  print("Created the stream");

  stream.listen((data) {
    print("DataReceived: "+data);
  }, onDone: () {
    print("Task Done");
  }, onError: (error) {
    print("Some Error");
  });
  
  print("code controller is here");
}

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

Here Single stream performs & giving the callback, but what if I want multiple streams to perform at the same time?

2 Answers

For it StreamGroup can be used to combine multiple streams

Add Dependency:

async: ^2.4.1

Use StreamGroup:

 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);
  });

}

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

You can also use rxdart package:

Depend on it:

dependencies:
  rxdart: ^0.24.1

now you can use Rx.merge to simply merge multiple streams together:

Rx.merge([
  Rx.timer(1, Duration(days: 10)),
  Stream.value(2)
])
.listen(print); // prints 2, 1

rxdart also has other methods such as combineLatest. You can learn more about the different methods of merging multiple streams here.

Related