Skip to content

Instantly share code, notes, and snippets.

@Hecatoncheir
Forked from azenla/event_loop.dart
Created February 20, 2017 13:31
Show Gist options
  • Save Hecatoncheir/80b203152a4a5ec2e7f7fe791be8c19e to your computer and use it in GitHub Desktop.
Save Hecatoncheir/80b203152a4a5ec2e7f7fe791be8c19e to your computer and use it in GitHub Desktop.
Simulation of the Dart Event Loop in Dart.
/// Dart is built around a timer, which basically schedules functions in a queue.
/// The Future class is essentially just sugar on top of the event loop.
/// To help people understand what the event loop actually does, I have written code which implements the event loop.
/// See https://www.dartlang.org/articles/event-loop/ for more information.
import "dart:async";
class EventLoop {
/// Function Queue.
static final List<Function> queue = [];
/// Microtask Queue.
static final List<Function> microtasks = [];
/// Add a Function to the queue.
static void run(Function function) {
print("Function");
queue.add(function);
}
static void runMicrotask(Function function) {
print("Microtask");
microtasks.add(function);
}
/// Execute events.
static void loop() {
// Execute microtasks.
while (microtasks.isNotEmpty) {
microtasks.removeAt(0)();
}
// Executes the events until there is no longer an event to execute.
while (queue.isNotEmpty) {
// Execute microtasks.
while (microtasks.isNotEmpty) {
microtasks.removeAt(0)();
}
queue.removeAt(0)();
}
if (microtasks.isNotEmpty || queue.isNotEmpty) {
loop(); // Loop again if there are still items to execute.
}
}
/// Main Function is called which queues up events.
/// It is called in a special zone which captures all futures and microtasks and runs them on the custom event loop.
static void callMainFunction(Function main, List<String> args) {
var zone = Zone.current.fork(specification: new ZoneSpecification(
scheduleMicrotask: (a, b, c, func) {
EventLoop.runMicrotask(func);
},
createTimer: (a, b, c, d, func) {
if (d == Duration.ZERO) {
EventLoop.run(func);
return null;
} else {
return new Timer(d, func);
}
}
));
zone.runUnary(main, args); // Queues up events.
loop(); // Run Event Loop.
}
}
void main() {
EventLoop.callMainFunction(_main, []);
}
void _main(List<String> args) {
int counter = 5;
// Simulates that futures queue up functions to be run after an action is completed.
decrement() {
print(counter);
counter--;
if (counter != 0) {
new Future(decrement);
}
}
decrement();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment