fold<S> method
- SinitialValue,
- Scombine(
- Sprevious,
- Telement
Combines a sequence of values by repeatedly applyingcombine.
Similar toIterable.fold, this function maintains a value,starting withinitialValue and updated for each element ofthis stream.For each element, the value is updated to the result of callingcombine with the previous value and the element.
When this stream is done, the returned future is completed withthe value at that time.For an empty stream, the future is completed withinitialValue.
If this stream emits an error, or the call tocombine throws,the returned future is completed with that error,and processing is stopped.
Example:
final result = await Stream.fromIterable([2, 6, 10, 8, 2]) .fold<int>(10, (previous, element) => previous + element);print(result); // 38Implementation
Future<S> fold<S>(S initialValue, S combine(S previous, T element)) { _Future<S> result = _Future<S>(); S value = initialValue; StreamSubscription<T> subscription = this.listen( null, onError: result._completeError, onDone: () { result._complete(value); }, cancelOnError: true, ); subscription.onData((T element) { _runUserCode(() => combine(value, element), (S newValue) { value = newValue; }, _cancelAndErrorClosure(subscription, result)); }); return result;}