Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use Stream.pipe in Dart?

Tags:

dart

I know how Stream.pipe is commonly used for reading and writing to files, but what is a good example of using it with a StreamController and a custom stream?

Edit: I have come up with an example on how Stream.pipe can be used, but nothing is output to the screen when this code is run. I would expect the array to pass through the transformer, double each number, pipe the output to the second controller, which then outputs the doubled number to the screen. However, I don't see any results.

import 'dart:async';

var stream = Stream.fromIterable([1, 2, 3, 4, 5]);

void main() {
  final controller1 = new StreamController();
  final controller2 = new StreamController();

  final doubler =
      new StreamTransformer.fromHandlers(handleData: (data, sink) {
      sink.add(data * 2);
  });

  controller1.stream.transform(doubler).pipe(controller2);
  controller2.stream.listen((data) => print(data));

}
like image 416
inspirnathan Avatar asked Jan 03 '23 01:01

inspirnathan


1 Answers

I figured out my own problem. I forgot to insert controller1.addStream(stream); so controller1 wasn't receiving a stream, which then couldn't be piped to controller2. Here is my finished code.

import 'dart:async';

var stream = Stream.fromIterable([1, 2, 3, 4, 5]);

void main() {
  final controller1 = new StreamController();
  final controller2 = new StreamController();

  controller1.addStream(stream);

  final doubler =
      new StreamTransformer.fromHandlers(handleData: (data, sink) {
      sink.add(data * 2);
  });

  controller1.stream.transform(doubler).pipe(controller2);
  controller2.stream.listen((data) => print(data));

}
like image 135
inspirnathan Avatar answered Jan 10 '23 21:01

inspirnathan