我是否缺少dart语言(或轻量级库)的集成功能,仅通过where()
测试就可以async
对可迭代对象执行操作?我目前正在使用自己的实现:
Future<Iterable<T>> whereAsync<T>(
Iterable<T> collection, Future<bool> Function(T) asyncTest) async {
Map<T, bool> mappedCollection = Map();
await Future.wait(collection.map((element) async =>
mappedCollection[element] = await asyncTest(element)));
return mappedCollection.entries
.where((entry) => entry.value)
.map((entry) => entry.key);
}
答案 0 :(得分:0)
我认为您的代码示例看起来比需要的复杂。另外,您应该尝试阅读有关Streams的内容,因为它们是迭代器的异步版本。
我试图制作自己的代码版本,我认为可以解决相同的问题:
import 'dart:async';
void main() {
final list = [1, 2, 3];
whereAsync(Stream.fromIterable(list), (e) => e != 2).forEach(print); // 1 3
}
Stream<T> whereAsync<T>(Stream<T> stream, FutureOr<bool> check(T input)) async* {
await for (var element in stream) {
if (await check(element)) {
yield element;
}
}
}