飞镖中的通道原语?
Channel primitive in dart?
Dart 中是否有像 Go 中那样的 channel
原语?我找到的最接近的是 StreamIterator.
用例是允许消费者一个一个地异步处理值。此外,如果没有值,它应该只是等待。
您可以使用流来做到这一点
import 'dart:async' show Stream, StreamController;
main() {
StreamController<int> sc = new StreamController<int>();
sc.stream.listen((e) => print(e));
for(int i = 0; i < 10; i++) {
sc.add(i);
}
}
中尝试
另见
- https://www.dartlang.org/docs/tutorials/streams/
- https://www.dartlang.org/articles/creating-streams/
你不能在 Dart 中 "just wait",尤其是在浏览器中。
Dart 中还有 async*
生成器函数可用于创建流。参见示例 Async/Await feature in Dart 1.8
一个"naive"翻译形式await for(var event in someStream)
import 'dart:async';
main() {
StreamController<int> sc = new StreamController<int>();
startProcessing(sc.stream);
for(int i = 0; i < 10; i++) {
sc.add(i);
}
}
Future startProcessing(Stream stream) async {
StreamSubscription subscr;
subscr = stream.listen((value) {
subscr.pause();
new Future.delayed(new Duration(milliseconds: 500)).then((_) {
print('Processed $value');
subscr.resume();
});
});
//await for(int value in stream) {
// await new Future.delayed(new Duration(milliseconds: 500)).then((_) {
// print('Processed $value');
// });
//}
}
实际实施采用不同的方法
The way the await-for loop is implemented uses a one-event buffer (to avoid repeatedly pausing and resuming).
参见 https://github.com/dart-lang/sdk/issues/24956#issuecomment-157328619
Dart 中是否有像 Go 中那样的 channel
原语?我找到的最接近的是 StreamIterator.
用例是允许消费者一个一个地异步处理值。此外,如果没有值,它应该只是等待。
您可以使用流来做到这一点
import 'dart:async' show Stream, StreamController;
main() {
StreamController<int> sc = new StreamController<int>();
sc.stream.listen((e) => print(e));
for(int i = 0; i < 10; i++) {
sc.add(i);
}
}
中尝试
另见
- https://www.dartlang.org/docs/tutorials/streams/
- https://www.dartlang.org/articles/creating-streams/
你不能在 Dart 中 "just wait",尤其是在浏览器中。
Dart 中还有 async*
生成器函数可用于创建流。参见示例 Async/Await feature in Dart 1.8
一个"naive"翻译形式await for(var event in someStream)
import 'dart:async';
main() {
StreamController<int> sc = new StreamController<int>();
startProcessing(sc.stream);
for(int i = 0; i < 10; i++) {
sc.add(i);
}
}
Future startProcessing(Stream stream) async {
StreamSubscription subscr;
subscr = stream.listen((value) {
subscr.pause();
new Future.delayed(new Duration(milliseconds: 500)).then((_) {
print('Processed $value');
subscr.resume();
});
});
//await for(int value in stream) {
// await new Future.delayed(new Duration(milliseconds: 500)).then((_) {
// print('Processed $value');
// });
//}
}
实际实施采用不同的方法
The way the await-for loop is implemented uses a one-event buffer (to avoid repeatedly pausing and resuming).
参见 https://github.com/dart-lang/sdk/issues/24956#issuecomment-157328619