Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge multiple Streams into a higher level Stream?

I have two streams, Stream<A> and Stream<B>. I have a constructor for a type C that takes an A and a B. How do I merge the two Streams into a Stream<C>?

like image 537
Brett Avatar asked Apr 12 '16 11:04

Brett


People also ask

Where do streams merge?

A watershed, or drainage basin, is the area that collects water for a stream. As smaller streams flow downhill, they often merge together to form larger streams. These smaller streams are called tributaries.


2 Answers

import 'dart:async' show Stream; import 'package:async/async.dart' show StreamGroup;  main() async {   var s1 = stream(10);   var s2 = stream(20);   var s3 = StreamGroup.merge([s1, s2]);   await for(int val in s3) {     print(val);   } }  Stream<int> stream(int min) async* {   int i = min;   while(i < min + 10) {     yield i++;   } } 

See also http://news.dartlang.org/2016/03/unboxing-packages-async-part-2.html

prints

10 20 11 21 12 22 13 23 14 24 15 25 16 26 17 27 18 28 19 29 
like image 106
Günter Zöchbauer Avatar answered Nov 05 '22 21:11

Günter Zöchbauer


You can use StreamZip in package:async to combine two streams into one stream of pairs, then create the C objects from that.

import "package:async" show StreamZip; ... Stream<C> createCs(Stream<A> as, Stream<B> bs) =>   new StreamZip([as, bs]).map((ab) => new C(ab[0], ab[1])); 
like image 30
lrn Avatar answered Nov 05 '22 20:11

lrn