Swift Combine: zip() operator

KD Knowledge Diet
1 min readJan 27, 2023

Let’s take a look at zip() operator. What zip() is doing is that it’s going to pair different elements or different items from the publisher. But it’s not going to wait for the latest element from the publisher. zip() operator is simply going to pick and tries to pair depending on the values that it is receiving from the both publishers.

zip()

let publisher1 = PassthroughSubject<Int, Never>() 
let publisher2 = PassthroughSubject<String, Never>()
publisher1.zip(publisher2)
.sink {
print($0, $1)
}
publisher1.send(1)
publisher2.send("2")
// 1, "2"
publisher1.send(2)
// not going to work

I prepared two publishers and zipped them. But as you can see from the code above, zipped publishers through zip() operator are not going to be called unless provided a pair. If you know combineLatest() operator, you can see the difference. With combineLatest(), when its first published value went down to the downstream, you can even receive the event from one publisher. But zip() is different because it always needs a pair of an emitted event to form a tuple value.

Conclusion

  • zip() operators combine multiple publishers.
  • zip() needs a pair of an event to emit the value.

--

--

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!