Skip to content

Instantly share code, notes, and snippets.

@xros
Created December 27, 2021 08:56
Show Gist options
  • Save xros/d6ae9e7565c1a3e86e5a57fc4d3b0889 to your computer and use it in GitHub Desktop.
Save xros/d6ae9e7565c1a3e86e5a57fc4d3b0889 to your computer and use it in GitHub Desktop.
fizz buzz with Stream (Asynchronous Programming in Dart)
Stream<String> fizzBuzz(int n) async* {
for (var i = 1; i <= n; i++) {
// await Future.delayed(Duration(milliseconds: 500));
if (i % 3 == 0 && i % 5 == 0) {
yield 'fizz buzz';
} else if (i % 3 == 0) {
yield 'fizz';
} else if (i % 5 == 0) {
yield 'buzz';
} else {
yield '$i';
}
}
}
Future<void> main() async {
final fizzbuzz = await fizzBuzz(15);
await for (var i in fizzbuzz) {
await Future.delayed(Duration(milliseconds: 500));
print(i);
}
}
@xros
Copy link
Author

xros commented Dec 27, 2021

output

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizz buzz

It waits 500 ms for each line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment