Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(121)

Side by Side Diff: pkg/scheduled_test/lib/src/utils.dart

Issue 12209073: Add a scheduled test library. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Make everything play nicely with the outside world. Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 library utils;
6
7 import 'dart:async';
8
9 /// Configures [future] so that its result (success or exception) is passed on
10 /// to [completer].
11 void chainToCompleter(Future future, Completer completer) {
12 future.then((value) => completer.complete(value),
13 onError: (e) => completer.completeError(e.error, e.stackTrace));
14 }
15
16 /// Prepends each line in [text] with [prefix].
17 String prefixLines(String text, {String prefix: '| '}) =>
18 text.split('\n').map((line) => '$prefix$line').join('\n');
19
20 /// Returns a [Future] that completes in [milliseconds].
21 Future sleep(int milliseconds) {
22 var completer = new Completer();
23 new Timer(milliseconds, (_) => completer.complete());
24 return completer.future;
25 }
26
27 /// Wraps [input] to provide a timeout. If [input] completes before
28 /// [milliseconds] have passed, then the return value completes in the same way.
29 /// However, if [milliseconds] pass before [input] has completed, [onTimeout] is
30 /// run and its result is passed to [input] (with chaining, if it returns a
31 /// [Future]).
32 ///
33 /// Note that timing out will not cancel the asynchronous operation behind
34 /// [input].
35 Future timeout(Future input, int milliseconds, onTimeout()) {
36 bool completed = false;
37 var completer = new Completer();
38 var timer = new Timer(milliseconds, (_) {
39 completed = true;
40 chainToCompleter(new Future.immediate(null).then((_) => onTimeout()),
41 completer);
42 });
43 input.then((value) {
44 if (completed) return;
45 timer.cancel();
46 completer.complete(value);
47 }).catchError((e) {
48 if (completed) return;
49 timer.cancel();
50 completer.completeError(e.error, e.stackTrace);
51 });
52 return completer.future;
53 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698