Dart 同步、异步

sync* 同步

1
2
3
4
5
6
7
8
9
10
11
12
13
main() {
print('==== start ====');

getList(10).forEach(print);

print('==== end ====');
}

Iterable<int> getList(int count) sync* {
for (int i = 0; i < count; i++) {
yield i;
}
}

执行结果:

sync 调用 sync

注意 yield* 的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
main() {
print('==== start ====');

getList(10).forEach(print);

print('==== end ====');
}


Iterable<int> getList(int count) sync* {
yield* generate(count);
}

Iterable<int> generate(int count) sync* {
for (int i = 0; i < count; i++) {
yield i;
}
}

执行结果:

async 异步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
main() {
print('==== start ====');

getList(5).then(print);

print('==== end ====');
}

Future<int> getList(int count) async {
await sleep();
for (int i = 0; i < count; i++) {
print('for $i');
}
return 99;
}

/// 延迟3秒
Future sleep() async {
return Future.delayed(Duration(seconds: 3));
}

执行结果:

async* + Stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
main() {
print('==== start ====');

getList(5).listen(print);

print('==== end ====');
}

Stream<int> getList(int count) async* {
for (int i = 0; i < count; i++) {
await Future.delayed(Duration(seconds: 1));

yield i;
}
}

执行结果:

async* 调用 async*

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
main() {
print('==== start ====');

getList(5).listen(print);

print('==== end ====');
}

Stream<int> getList(int count) async* {
yield* generate(count);
}

Stream<int> generate(int count) async* {
for (int i = 0; i < count; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}

执行结果: