Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stanlee321/8a59185a854f46c13ee8af0ed2a0a897 to your computer and use it in GitHub Desktop.
Save stanlee321/8a59185a854f46c13ee8af0ed2a0a897 to your computer and use it in GitHub Desktop.
Streams, stream controller, and event loops in Dart.
import 'dart:async';
import 'dart:math';
/*
* Findings:
* streams can be single or broadcast, but not sure why the diff.
* can check if a stream is broadcast with isBroadcast
* StreamController make it easy to use a stream and send it events
*/
main() {
// why wouldn't I always want to use broadcast?
var controller = new StreamController.broadcast();
var stream = controller.stream;
stream.listen((n) => print(" Received $n"));
print("Start first loop");
for (var i = 0; i < 5; i++) {
// simulate pumping events into the event queue
print("Pushing $i from first loop");
new Timer(0, (t) => controller.add(i));
}
print("Finished first loop");
print("Start second loop");
for (var i = 10; i < 15; i++) {
// simulate pumping events into the event queue
print("Pushing $i from second loop");
controller.add(i);
}
print("Finish second loop");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment