Created
February 28, 2019 12:08
-
-
Save graphicbeacon/6bbd058ab013a7d2364ef7c3c1d98014 to your computer and use it in GitHub Desktop.
Code snippet for "How to use Streams in Dart (Part 2)" series
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
void main() { | |
var controller = StreamController<num>(); | |
// Create StreamTransformer with transformer closure | |
var streamTransformer = StreamTransformer<num, num>.fromHandlers( | |
handleData: (num data, EventSink sink) { | |
sink.add(data * 2); | |
}, | |
handleError: (error, stacktrace, sink) { | |
sink.addError('Something went wrong: $error'); | |
}, | |
handleDone: (sink) { | |
sink.close(); | |
}, | |
); | |
// Call the `transform` method on the controller's stream | |
// while passing in the stream transformer | |
var controllerStream = controller.stream.transform(streamTransformer); | |
// Just print out transformations to the console | |
controllerStream.listen(print); | |
// Add data to stream to see transformations in effect | |
controller.sink.add(1); // 2 | |
controller.sink.add(2); // 4 | |
controller.sink.add(3); // 6 | |
controller.sink.add(4); // 8 | |
controller.sink.add(5); // 10 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment