在为我的项目编写一些单元测试时,我遇到了一个有趣的问题。
以下是用户可用于放置标记的地图:
class DomainMap {
static const _DEFAULT_COORDINATE = const Coordinate(40.73, -73.93);
final ReverseGeocodingStrategy _geocodingStrategy;
final RouteDefinitionStrategy _assemblyStrategy;
final List<_IdentifiedCoordinate> _addressed = [];
final List<Coordinate> _markers = [];
final _Route _route = _Route();
Coordinate get defaultCoordinate => _DEFAULT_COORDINATE;
DomainMap(this._geocodingStrategy, this._assemblyStrategy);
Stream<MarkersUpdateEvent> mark(Coordinate coordinate) async* {
_markers.add(coordinate);
yield _assembleMarkersUpdate();
final Address address = await _geocodingStrategy.geocode(coordinate);
_addressed.add(_IdentifiedCoordinate(coordinate, address));
if (_addressed.length > 1) {
final Iterable<Coordinate> assembledPolyline =
await _assemblyStrategy.buildRoute(BuiltList(_addressed
.map((identifiedCoordinate) => identifiedCoordinate.address)));
assembledPolyline.forEach(_route.add);
yield _assembleMarkersUpdate();
}
}
MarkersUpdateEvent _assembleMarkersUpdate() =>
MarkersUpdateEvent(BuiltList.from(_markers), _route.readOnly);
}
class _Route {
final List<Coordinate> _points = [];
Iterable<Coordinate> get readOnly => BuiltList(_points);
void add(final Coordinate coordinate) => _points.add(coordinate);
void addAll(final Iterable<Coordinate> coordinate) => _points.addAll(coordinate);
}
这是一个单元测试,检查在这里的第二个标记应该是一个返回的路由:
test("mark, assert that on second mark at first just markers update is published, and then the polyline update too", () async {
final Coordinate secondCoordinate = plus(givenCoordinate, 1);
final givenRoute = [
givenCoordinate,
minus(givenCoordinate, 1),
plus(givenCoordinate, 1)
];
when(geocodingStrategy.geocode(any)).thenAnswer((invocation) => Future.value(Address(invocation.positionalArguments[0].toString())));
when(assemblyStrategy.buildRoute(any))
.thenAnswer((_) => Future.value(givenRoute));
final expectedFirstUpdate =
MarkersUpdateEvent([givenCoordinate, secondCoordinate], []);
final expectedSecondUpdate =
MarkersUpdateEvent([givenCoordinate, secondCoordinate], givenRoute);
final DomainMap map = domainMap();
map.mark(givenCoordinate)
//.forEach(print) //Important
;
expect(map.mark(secondCoordinate),
emitsInOrder([expectedFirstUpdate, expectedSecondUpdate]));
}, timeout: const Timeout(const Duration(seconds: 10)));
当我这样运行它时,测试失败并说该流只发出一个值 - 一个更新事件,只有markers
字段不为空,只包含一个secondCoordinate
。但是当我取消注释forEach
时,测试就通过了。
据我所知 - async*
方法不会被调用,直到流的值不被请求,所以当调用forEach
时 - 函数被执行直到结束。因此,如果我请求所有流(从第一次调用返回)值 - 执行方法,填充markers
列表,并在预期状态下执行第二次执行。
我正确理解async*
语义吗?这是一种让这个函数渴望而不是懒惰的方法(我不想请求不需要的流的值)?
是的,async*
在返回的流上调用listen
之后懒惰地调用该函数。如果你从不听,那就没有任何反应。它甚至是异步的,而不是直接响应listen
调用。
所以,如果你肯定需要发生一些事情,但只是需要查看响应,那么你就不能使用async*
函数来做某事。
您可能想要做的是有条件地填充流,但仅限于实际收听流。这是一个非传统的操作序列,它与async*
甚至async
语义都不匹配。您必须为要完成的操作做好准备,然后稍后才会收听流。这表明将操作分为两个部分,一个用于请求的async
,一个async*
用于响应,并在两者之间分享未来,这意味着两次听同一个未来,一个明显的非async
行为。
我建议拆分流行为并使用StreamController
。
Stream<MarkersUpdateEvent> mark(Coordinate coordinate) {
var result = StreamController<MarkersUpdateEvent>();
() async {
_markers.add(coordinate);
result.add(_assembleMarkersUpdate());
final Address address = await _geocodingStrategy.geocode(coordinate);
_addressed.add(_IdentifiedCoordinate(coordinate, address));
if (_addressed.length > 1) {
final Iterable<Coordinate> assembledPolyline =
await _assemblyStrategy.buildRoute(BuiltList(_addressed
.map((identifiedCoordinate) => identifiedCoordinate.address)));
assembledPolyline.forEach(_route.add);
result.add(_assembleMarkersUpdate());
}
result.close();
}().catchError(result.addError);
return result.stream;
}
这样,程序逻辑独立于是否有人监听流而运行。您仍然会缓冲所有流事件。没有真正的方法可以避免这种情况,除非您可以在以后计算它们,因为您无法知道何时有人可能会收听返回的流。它不必在返回时立即发生。