Movatterモバイル変換


[0]ホーム

URL:


menu
  1. Dart
  2. dart:async
  3. Stream<T>
  4. fold<S> method
fold
description

fold<S> method

Future<S>fold<S>(
  1. SinitialValue,
  2. Scombine(
    1. Sprevious,
    2. 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); // 38

Implementation

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;}
  1. Dart
  2. dart:async
  3. Stream<T>
  4. fold<S> method
Stream class

[8]ページ先頭

©2009-2025 Movatter.jp