inspirnathan
inspirnathan

Reputation: 381

How do you use Stream.pipe in 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));

}

Upvotes: 6

Views: 6770

Answers (1)

inspirnathan
inspirnathan

Reputation: 381

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

}

Upvotes: 10

Related Questions