Skip to content

Instantly share code, notes, and snippets.

@mraleph
Last active December 19, 2015 17:29
Show Gist options
  • Save mraleph/5991990 to your computer and use it in GitHub Desktop.
Save mraleph/5991990 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:html' as html;
stream() {
final sc = new StreamController();
spawn(ms, id) =>
new Timer.periodic(new Duration(milliseconds: ms), (_) => sc.add(id));
spawn(250, 1);
spawn(1000, 2);
spawn(1500, 3);
return sc.stream;
}
void main() {
html.document.body.appendHtml('<div id="out" />');
final q = [];
stream().listen((msg) {
q.add(msg);
if (q.length > 10) q.removeAt(0);
html.query("#out").innerHtml = q.map((id) => "<div class='proc-${id}'>Process ${id}</div>").join('');
});
}
import 'dart:html' as html;
void main() {
html.document.body.appendHtml('<div id="out" style="width: 100px; height: 100px;"/>');
offset(em) =>
(e) => e.client - em.client.topLeft;
final out = html.query("#out");
out.onMouseMove.map(offset(out)).listen((p) {
out.innerHtml = "(${p.x}, ${p.y})";
});
}
import 'dart:async';
import 'dart:math' as math;
final random = new math.Random();
randomDuration(max) => new Duration(milliseconds: random.nextInt(max));
fakeSearch(kind) =>
(sc, query) =>
new Timer(randomDuration(100), () { sc.add([kind, query]); });
final web1 = fakeSearch("web1");
final web2 = fakeSearch("web2");
final image1 = fakeSearch("image1");
final image2 = fakeSearch("image2");
final video1 = fakeSearch("video1");
final video2 = fakeSearch("video2");
fastest(query, servers) {
final sc = new StreamController();
for (var server in servers)
server(sc, query);
return sc.stream.take(1);
}
class Timeout { }
Future<List> search(query) {
final sc = new StreamController();
fastest(query, [web1, web2]).listen(sc.add);
fastest(query, [image1, image2]).listen(sc.add);
fastest(query, [video1, video2]).listen(sc.add);
new Timer(const Duration(milliseconds: 50), () => sc.add(new Timeout()));
return sc.stream.takeWhile((m) => m is !Timeout).take(3).toList();
}
void main() {
search("Dart").then(print);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment