This is Understanding Combine, written by Matt Neuburg. Corrections and suggestions are greatly appreciated (you can comment here). So are donations; please consider keeping me going by funding this work at http://www.paypal.me/mattneub. Or buy my books: the current (and final) editions are iOS 15 Programming Fundamentals with Swift and Programming iOS 14. Thank you!
.reduce
(Publishers.Reduce) is just like the reduce
sequence method. You supply two parameters: an initial output value and a function. The output value is what is being accumulated. The function itself takes two parameters: the accumulated output value, and a newly arrived value from upstream; it returns a new output value, which is now the accumulated value and is supplied as the first parameter to the next call to the function when the next value arrives from upstream. This goes on until a .finished
completion is received. At that point, the output value that was returned from the last call to the function is emitted downstream (followed by a .finished
completion).
Here’s a toy example, just to show the syntax:
[1,2,3].publisher
.reduce(0) {
return $0 + $1
}
That function returns 1
, then 3
, then 6
— and then the .finished
completion arrives from upstream, so the operator sends 6
downstream, followed by a .finished
completion.
Similar to .reduce
is .tryReduce
(Publishers.TryReduce), which adds the ability for the function to throw. This can happen at any point during the arrival of incoming values. If it does throw, it cancels the upstream publisher and sends the resulting error downstream as a failure.