fold()
is a terminal operator: it does not return another Flow
, but rather
a result from operating on that Flow
.
fold()
takes an initial value (of some arbitrary type) and a lambda expression
or other function type. For the first item emitted by the upstream Flow
,
fold()
calls the lambda expression with the initial value and that emitted item,
and fold()
saves the value that the lambda expression evaluates to. For
the second item emitted by the upstream Flow
, fold()
calls the lambda expression
with the result of the first lambda expression, along with the second emitted item,
and fold()
saves the value from the lambda expression. This process continues
with each emitted item, until the upstream Flow
completes. At that point,
fold()
returns whatever the last lambda expression invocation evaluated to.
If the upstream Flow
completes without ever emitting anything, fold()
returns
the initial value, unmodified.
In this sample, we have a custom sum()
operator that sums a Flow
of Int
values. We start with 0
and add each emitted value to the previous sum.