Florian Loitsch | 310385a | 2016-02-11 14:53:44 +0100 | [diff] [blame] | 1 | // Copyright (c) 2016, 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 | import "dart:async"; |
| 6 | import "package:expect/expect.dart"; |
| 7 | import "package:async_helper/async_helper.dart"; |
| 8 | |
| 9 | var events = []; |
| 10 | |
| 11 | var timer; |
| 12 | ticker(period) async* { |
| 13 | var sc; |
| 14 | sc = new StreamController(onListen: () { |
| 15 | events.add("listen"); |
| 16 | timer = new Timer.periodic(period, (_) { |
| 17 | sc.add(null); |
| 18 | }); |
| 19 | }, onCancel: () { |
| 20 | events.add("cancel"); |
| 21 | timer.cancel(); |
| 22 | }); |
| 23 | |
| 24 | try { |
| 25 | var counter = 0; |
| 26 | await for (var tick in sc.stream) { |
| 27 | counter++; |
| 28 | } |
| 29 | } finally { |
| 30 | events.add("finally"); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | void main() { |
| 35 | asyncStart(); |
| 36 | events.add("main"); |
| 37 | final subscription = |
| 38 | ticker(const Duration(milliseconds: 20)).listen((val) { }); |
| 39 | |
| 40 | bool cancelFinished = false; |
| 41 | new Timer(const Duration(milliseconds: 100), () async { |
| 42 | // Despite the cancel call below, the stream doesn't stop. |
| 43 | // The async* function is not blocked at any await (since the inner timer |
| 44 | // continuously ticks), but since there/ is no yield-point in the function |
| 45 | // it won't cancel. |
| 46 | new Timer(const Duration(milliseconds: 30), () { |
| 47 | Expect.isFalse(cancelFinished); |
| 48 | Expect.listEquals(["main", "listen", "invoke cancel"], events); |
| 49 | timer.cancel(); |
| 50 | asyncEnd(); |
| 51 | }); |
| 52 | |
| 53 | events.add("invoke cancel"); |
| 54 | await subscription.cancel(); |
| 55 | // This line should never be reached, since the cancel-future doesn't |
| 56 | // complete. |
| 57 | cancelFinished = true; |
| 58 | }); |
| 59 | } |