| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2014, 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 // VMOptions=--enable_async |
| 6 |
| 7 import "dart:async"; |
| 8 import "package:expect/expect.dart"; |
| 9 import "package:async_helper/async_helper.dart"; |
| 10 |
| 11 class Trace { |
| 12 String trace = ""; |
| 13 record(x) { |
| 14 trace += x.toString(); |
| 15 } |
| 16 toString() => trace; |
| 17 } |
| 18 |
| 19 |
| 20 Stream makeMeAStream() { |
| 21 return timedCounter(5); |
| 22 } |
| 23 |
| 24 Trace t1 = new Trace(); |
| 25 |
| 26 consumeOne() async { |
| 27 // Equivalent to await for (x in makeMeAStream()) { ... } |
| 28 var s = makeMeAStream(); |
| 29 var it = new StreamIterator(s); |
| 30 while (await it.moveNext()) { |
| 31 var x = it.current; |
| 32 t1.record(x); |
| 33 } |
| 34 t1.record("X"); |
| 35 } |
| 36 |
| 37 Trace t2 = new Trace(); |
| 38 |
| 39 consumeTwo() async { |
| 40 await for (var x in makeMeAStream()) { |
| 41 t2.record(x); |
| 42 } |
| 43 t2.record("X"); |
| 44 } |
| 45 |
| 46 main() { |
| 47 var f1 = consumeOne(); |
| 48 t1.record("T1:"); |
| 49 |
| 50 var f2 = consumeTwo(); |
| 51 t2.record("T2:"); |
| 52 |
| 53 asyncStart(); |
| 54 Future.wait([f1, f2]).then((_) { |
| 55 print("Trace 1: $t1"); |
| 56 print("Trace 2: $t2"); |
| 57 Expect.equals("T1:12345X", t1.toString()); |
| 58 Expect.equals("T2:12345X", t2.toString()); |
| 59 asyncEnd(); |
| 60 }); |
| 61 } |
| 62 |
| 63 |
| 64 // Create a stream that produces numbers [1, 2, ... maxCount] |
| 65 Stream timedCounter(int maxCount) { |
| 66 StreamController controller; |
| 67 Timer timer; |
| 68 int counter = 0; |
| 69 |
| 70 void tick(_) { |
| 71 counter++; |
| 72 controller.add(counter); // Ask stream to send counter values as event. |
| 73 if (counter >= maxCount) { |
| 74 timer.cancel(); |
| 75 controller.close(); // Ask stream to shut down and tell listeners. |
| 76 } |
| 77 } |
| 78 |
| 79 void startTimer() { |
| 80 timer = new Timer.periodic(const Duration(milliseconds: 10), tick); |
| 81 } |
| 82 |
| 83 void stopTimer() { |
| 84 if (timer != null) { |
| 85 timer.cancel(); |
| 86 timer = null; |
| 87 } |
| 88 } |
| 89 |
| 90 controller = new StreamController( |
| 91 onListen: startTimer, |
| 92 onPause: stopTimer, |
| 93 onResume: startTimer, |
| 94 onCancel: stopTimer); |
| 95 |
| 96 return controller.stream; |
| 97 } |
| OLD | NEW |