Created
March 9, 2020 06:11
-
-
Save AlexKenbo/a11ebe596e41458993d4fb66b1469345 to your computer and use it in GitHub Desktop.
Stream transform
This file contains hidden or 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