Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active December 8, 2025 20:30
Show Gist options
  • Select an option

  • Save PlugFox/148630c3ab6f9f14adc3e0a26ee76d9e to your computer and use it in GitHub Desktop.

Select an option

Save PlugFox/148630c3ab6f9f14adc3e0a26ee76d9e to your computer and use it in GitHub Desktop.
Dart async generator with StreamController
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