Created
April 7, 2019 19:25
-
-
Save Alexisvt/d28dfee961281ecec12df9ea10ac4620 to your computer and use it in GitHub Desktop.
Simple example of how Streams works in Dart
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 addLessThanFive(StreamController controller, int value) { | |
if(value < 5) { | |
controller.sink.add(value); | |
} else { | |
controller.sink.addError(StateError('$value is not less than 5')); | |
} | |
} | |
void main() { | |
final controller = StreamController(); | |
// in this example we are passing integer values but we can pass any value to the stream | |
addLessThanFive(controller, 1); | |
addLessThanFive(controller, 2); | |
addLessThanFive(controller, 3); | |
addLessThanFive(controller, 4); | |
addLessThanFive(controller, 5); | |
// example of any value been passed to the stream | |
controller.sink.add(null); | |
controller.sink.add([10, 12.3, 'another string']); | |
controller.close(); | |
// this will rise and unhandled exception | |
// addLessThanFive(controller, 0); | |
controller.stream.listen(print, onError: print, onDone: () { | |
print('done'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment