Skip to content

Instantly share code, notes, and snippets.

@sethladd
Created February 8, 2013 21:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sethladd/4742145 to your computer and use it in GitHub Desktop.
Save sethladd/4742145 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");
}
@sethladd
Copy link
Author

I can replace new Timer(0, ... with new Future.immediate because immediate will run in the next event loop cycle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment