Swift Combine: count() operator
Let’s talk about count()
operator. The whole purpose of count()
operator is to depict that how many values will be emitted by the publisher
count()
let publisher = ["A", "B", "C", "D", "E"].publisherpublisher
.count()
.sink {
print($0) // 5
}
In order to demonstrate count()
operator, I made a publisher of an array of strings. When you use count()
operator like the example above, you can see the final result is 5
. This is the total number of elements in the array. count()
is very simple to understand.
Then, how ‘count()’ works with subject?
let publisher = PassthroughSubject<Int, Never>() publisher
.count()
.sink {
print($0)
}publisher.send(1) // nothing will occur
publisher.send(2) // nothing will occur
publisher.send(3) // nothing will occur
publisher.send(4) // nothing will occur
publisher.send(completion: .finished) // 4
When using count()
operator, when you send an event, it will never update publisher.count().sink()
. You need to send .finished
event to receive the final result with the count.
Conclusion
count()
sinks the total number of elements in the array- When using subject with
count()
,count()
needs.finished
event.