Async Calls in Flutter

Synchronous/asynchronous generator in function

  1. await for wait till command finished
  2. async* (async each) for a stream whenever there is an update in stream
  3. yield* (yield each) for returning an update from a stream
import 'dart:async';
import 'dart:io';

main() {
listenCountDown();
}

listenCountDown() async {
await for (var tick in countUp()) {
print("countDown $tick");
}
}

Stream<int> countDown() async* {
var i = 1000;
while (true) {
sleep(new Duration(seconds: 1));
yield i--;
}
}

When we want to use more than one await for, we should separate into 2 functions, if not another await for will be never executed.

import 'dart:async';
import 'dart:io';

main() {
listenCountDown();
listenCountUp();
}

listenCountDown() async {
await for (var tick in countUp()) {
print("countDown $tick");
}
}

listenCountUp() async {
await for (var tick in countDown()) {
print("countUp $tick");
}
}

Stream<int> countUp() async* {
var i = 0;
while (true) {
sleep(new Duration(seconds: 1));
yield i++;
}
}

Stream<int> countDown() async* {
var i = 1000;
while (true) {
sleep(new Duration(seconds: 1));
yield i--;
}
}

Other way, we can refactor it and use listen for stream changes:

import 'dart:async';
import 'dart:io';

main() {
countUp().listen((tick){
print("counting up $tick");
});
countDown().listen((tick){
print("counting down $tick");
});
}

Stream<int> countUp() async* {
var i = 0;
while (true) {
sleep(new Duration(seconds: 1));
yield i++;
}
}

Stream<int> countDown() async* {
var i = 1000;
while (true) {
sleep(new Duration(seconds: 1));
yield i--;
}
}