Last active
August 29, 2015 14:16
-
-
Save mraleph/5a979f73d5c07f520e14 to your computer and use it in GitHub Desktop.
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
<div id="result"></div> |
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
// | |
// This is straightforward port the first example from | |
// David Nolen's blog post about CSP | |
// | |
// http://swannodette.github.io/2013/07/12/communicating-sequential-processes/ | |
// | |
import 'dart:async'; | |
import 'dart:html'; | |
import 'dart:collection'; | |
/// Message sent from one process into the 'channel' (in Dart they are called streams). | |
class Msg { | |
final source; | |
final counter; | |
Msg(this.source, this.counter); | |
toString() => "Process #${source}: ${counter}"; | |
} | |
/// Spawn a process with [id] that emits [Msg] with the given [period] into | |
/// the given channel [ch] and counts how many messages it has emitted. | |
process(id, period, ch) async { | |
var counter = 0; | |
await for (var tick in new Stream.periodic(period)) { | |
ch.add(new Msg(id, counter++)); | |
} | |
} | |
main() async { | |
final el = document.querySelector("#result"); | |
final ch = new StreamController(); | |
// Spawn three processes. | |
process(0, const Duration(milliseconds: 250), ch); | |
process(1, const Duration(milliseconds: 1000), ch); | |
process(2, const Duration(milliseconds: 1500), ch); | |
// Accumulate last 10 emitted messages and render them. | |
final frame = new Queue(); | |
await for (var msg in ch.stream) { | |
frame.add(msg); | |
if (frame.length > 10) { | |
frame.removeFirst(); | |
} | |
el.innerHtml = frame.map((msg) => '<div class="proc-${msg.source}">${msg}</div>').join(''); | |
} | |
} |
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
#result { | |
font-family: 'Inconsolata', monospace; | |
font-weight: bold; | |
width: 10em; | |
margin-left: auto; | |
margin-right: auto; | |
font-size: 1.5em; | |
} | |
.proc-0 { | |
color: #dfaf8f; | |
} | |
.proc-1 { | |
color: #f0dfaf; | |
} | |
.proc-2 { | |
color: #bfebbf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment