Swift Combine: count() operator

KD Knowledge Diet
1 min readFeb 15, 2023

--

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.

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!

No responses yet