Swift Combine: scan() method. The most useful operator
There’s another useful operator in the combine framework. It’s called scan()
. Now let’s check out this useful operator.
Examples
import Combinelet publisher = (1...10).publisher// scan's 1st argument is the initial result
// closure's 1st argument is the nextResult
// closure's 2nd argument is the values
// closure's return type is the result
publisher.scan(0) { nextReuslt, value -> Int in
return nextReuslt + value // appending item to the array
}
.sink { value in
print(value) // 1,3,6,10,15,21,28,36,45,55
}
I created a sequence which goes from 1 to 10. You can simply call publisher.scan()
.
Take a look at the signature for the scan operator really carefully.
The first argument is initialResult, which can be of any type. So, this is up to you, whatever type that you want to provide.
The next argument is actually a closure that takes in the type of the first argument that you have set up and the second argument is the type of integer which you can see the value is currently integer.
So, If I go ahead and start using the scan type, it is going to return the type that I specified initially.
Finally, in sink()
method, you get the steam of the partial result.
Conclusion
- scan’s 1st argument is the initial result, you can specify datatype here.
- scan’s 2nd argument is a closure that takes first argument of partial result and the second argument of value.
- When receiving values, you receive the stream of partial results.