What is combineLatest() operator in Swift Combine framework

Manish Pathak
2 min readJun 19, 2023

It is yet another combining operator.

combineLatest() is basically going to combine two different publishers. The great thing is that both of those publishers can have different types. Do you know merge() the operator? It’s also combining publishers but merge() requires publishers to have the same type.

combineLastest()’s return value

When you are using combineLatest(), what you are going to get as a sequence is tuple. The latest value from each of the publisher is combined together into a tuple.

let publisher1 = PassthroughSubject<Int, Never>()
let publisher2 = PassthroughSubject<String, Never>()publisher1.combineLatest(publisher2)
.sink { // receiveValue ((Int, String) -> Void)
print($0, $1)
}publisher1.send(0) // nothing works

I created two publishers with two different types. One is getting Integer and another is getting String. You are neither receiving Int nor String, but you are going to receive ((Int, String)) Tuple Value. So, when you send an event from publisher1 alone, it simply doesn’t work. You must have a pair of values from publisher1 and publisher2 when it’s your first time to publisher.

let publisher1 = PassthroughSubject<Int, Never>()
let publisher2 = PassthroughSubject<String, Never>()publisher1.combineLatest(publisher2)
.sink { // receiveValue ((Int, String) -> Void)
print($0)
}// You need to send a pair of values
publisher1.send(0)
publisher2.send("hello world")
// 0
// "hello world"// After you first published a pair of values
// Now your publisher can get value when only one publisher
// sends an event
publisher1.send(1)
// 1

Like this, you must send a pair of values. Then, in sink(), you can receive the tuple. But after publishing the first tuple value with publisher1 and publisher2 , when you publisher a new value, left-side int is also passed down to the downstream.

More generally, the observable produced by combineLatest emits its first value when all the observables first emits a value, and subsequent values are emitted when any of the observables emits a value.

Conclusion

  • combineLatest() combine multiple publishers
  • combineLatest() returns tuple in the sink().
  • combineLatest() needs a paired event.

--

--

Manish Pathak
Manish Pathak

Written by Manish Pathak

A dreamer, lover and Android/iOS developer

No responses yet