W3cubDocs

/Dart 2

fold<S> method

Future<S> fold <S>(S initialValue, S combine(S previous, T element))

Combines a sequence of values by repeatedly applying combine.

Similar to Iterable.fold, this function maintains a value, starting with initialValue and updated for each element of this stream. For each element, the value is updated to the result of calling combine with the previous value and the element.

When this stream is done, the returned future is completed with the value at that time. For an empty stream, the future is completed with initialValue.

If this stream emits an error, or the call to combine throws, the returned future is completed with that error, and processing is stopped.

Implementation

Future<S> fold<S>(S initialValue, S combine(S previous, T element)) {
  _Future<S> result = new _Future<S>();
  S value = initialValue;
  StreamSubscription subscription;
  subscription = this.listen(
      (T element) {
        _runUserCode(() => combine(value, element), (S newValue) {
          value = newValue;
        }, _cancelAndErrorClosure(subscription, result));
      },
      onError: result._completeError,
      onDone: () {
        result._complete(value);
      },
      cancelOnError: true);
  return result;
}

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dartlang.org/stable/2.0.0/dart-async/Stream/fold.html