Last active
December 8, 2025 20:30
-
-
Save PlugFox/148630c3ab6f9f14adc3e0a26ee76d9e to your computer and use it in GitHub Desktop.
Dart async generator with StreamController
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:async'; | |
| void main() => gen().take(7).forEach(print); | |
| Stream<String> gen() { | |
| final controller = StreamController<String>(); | |
| void onCancel(void Function() fn) { | |
| var temp = controller.onCancel ?? () {}; | |
| controller.onCancel = () { | |
| temp(); | |
| fn(); | |
| }; | |
| } | |
| void push(String value) => controller.add(value); | |
| onCancel(() => print('* cancel')); | |
| controller.onListen = () { | |
| print('* listen'); | |
| { | |
| final timer = Timer.periodic(Duration(seconds: 1), (_) => push('1')); | |
| onCancel(() => timer.cancel()); | |
| } | |
| { | |
| final timer = Timer.periodic(Duration(seconds: 2), (_) => push('2')); | |
| onCancel(() => timer.cancel()); | |
| } | |
| { | |
| final timer = Timer.periodic(Duration(seconds: 3), (_) => push('3')); | |
| onCancel(() => timer.cancel()); | |
| } | |
| }; | |
| return controller.stream; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment