Dart by Example: Async*

  1. import 'dart:async';
  2. main() async {
  3. await for (String msg in printNumbersDownAsync(5)) {
  4. print(msg);
  5. }
  6. }
  7. Stream printNumbersDownAsync(int n) async* {
  8. int k = n;
  9. while (k >= 0) {
  10. yield await loadMessageForNumber(k--);
  11. }
  12. }
  13. Future loadMessageForNumber(int i) async {
  14. await new Future.delayed(new Duration(milliseconds: 50));
  15. if (i % 2 == 0) {
  16. return '$i is even';
  17. } else {
  18. return '$i is odd';
  19. }
  20. }
  21.  
  1. $ dart async_star.dart
  2. 5 is odd
  3. 4 is even
  4. 3 is odd
  5. 2 is even
  6. 1 is odd
  7. 0 is even

by @jryanio | source | license