OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, 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 // This is a regression test for issue 22853. |
| 6 |
| 7 import "dart:async"; |
| 8 import "package:expect/expect.dart"; |
| 9 import "package:async_helper/async_helper.dart"; |
| 10 |
| 11 main() { |
| 12 var list = []; |
| 13 var sync = new Sync(); |
| 14 f() async* { |
| 15 list.add("*1"); |
| 16 yield 1; |
| 17 await sync.wait(); |
| 18 sync.release(); |
| 19 list.add("*2"); |
| 20 yield 2; |
| 21 list.add("*3"); |
| 22 }; |
| 23 var stream = f(); |
| 24 var sub = stream.listen(list.add); |
| 25 |
| 26 asyncStart(); |
| 27 return sync.wait().whenComplete(() { |
| 28 Expect.listEquals(list, ["*1", 1]); |
| 29 sub.pause(); |
| 30 return sync.wait(); |
| 31 }).whenComplete(() { |
| 32 Expect.listEquals(list, ["*1", 1, "*2"]); |
| 33 sub.cancel(); |
| 34 new Future.delayed(new Duration(milliseconds: 200), () { |
| 35 // Should not have yielded 2 or added *3 while paused. |
| 36 Expect.listEquals(list, ["*1", 1, "*2"]); |
| 37 asyncEnd(); |
| 38 }); |
| 39 }); |
| 40 } |
| 41 |
| 42 /** |
| 43 * Allows two asynchronous executions to synchronize. |
| 44 * |
| 45 * Calling [wait] and waiting for the returned future to complete will |
| 46 * wait for the other executions to call [wait] again. At that point, |
| 47 * the waiting execution is allowed to continue (the returned future completes), |
| 48 * and the more recent call to [wait] is now the waiting execution. |
| 49 */ |
| 50 class Sync { |
| 51 Completer _completer = null; |
| 52 // Release whoever is currently waiting and start waiting yourself. |
| 53 Future wait([v]) { |
| 54 if (_completer != null) _completer.complete(v); |
| 55 _completer = new Completer(); |
| 56 return _completer.future; |
| 57 } |
| 58 |
| 59 // Release whoever is currently waiting. |
| 60 void release([v]) { |
| 61 if (_completer != null) { |
| 62 _completer.complete(v); |
| 63 _completer = null; |
| 64 } |
| 65 } |
| 66 } |
OLD | NEW |