Provide trace in single transformer (#1607)

This commit is contained in:
Simon Binder 2021-12-29 11:26:50 +01:00
parent 70e83b5a74
commit bce13f150f
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
2 changed files with 25 additions and 11 deletions

View File

@ -4,16 +4,17 @@ import 'dart:async';
/// that each list is a singleton or empty.
StreamTransformer<List<T>, T?> singleElementsOrNull<T>() {
return StreamTransformer.fromHandlers(handleData: (data, sink) {
T? result;
try {
if (data.isEmpty) {
sink.add(null);
} else {
sink.add(data.single);
if (data.isNotEmpty) {
result = data.single;
}
} catch (e) {
sink.addError(
StateError('Expected exactly one element, but got ${data.length}'));
throw StateError('Expected exactly one element, but got ${data.length}');
}
sink.add(result);
});
}
@ -21,11 +22,14 @@ StreamTransformer<List<T>, T?> singleElementsOrNull<T>() {
/// that each list is a singleton.
StreamTransformer<List<T>, T> singleElements<T>() {
return StreamTransformer.fromHandlers(handleData: (data, sink) {
T single;
try {
sink.add(data.single);
single = data.single;
} catch (e) {
sink.addError(
StateError('Expected exactly one element, but got ${data.length}'));
throw StateError('Expected exactly one element, but got ${data.length}');
}
sink.add(single);
});
}

View File

@ -22,8 +22,15 @@ void main() {
final controller = StreamController<List<int>>();
final stream = controller.stream.transform(singleElements());
expectLater(stream,
emitsInOrder([1, emitsError(anything), 2, emitsError(anything)]));
expectLater(
stream,
emitsInOrder([
1,
emitsError(_stateErrorWithTrace),
2,
emitsError(_stateErrorWithTrace)
]),
);
controller
..add([1])
@ -38,3 +45,6 @@ void main() {
expect(stream.transform(singleElementsOrNull()), emits(isNull));
});
}
Matcher _stateErrorWithTrace =
isStateError.having((e) => e.stackTrace, 'stackTrace', isNotNull);