combineLatest

Combine Mid-level Swift 5.1+ iOS 13+ Reviewed By Alok Singh

Predict the output

What does this print?

let a = PassthroughSubject<Int, Never>()
let b = PassthroughSubject<String, Never>()
a.combineLatest(b)
    .sink { print($0, $1) }
    .store(in: &cancellables)
a.send(1)
a.send(2)
b.send("x")
a.send(3)
Options
Hint 1 of 1

Nothing is emitted until both have sent at least once.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B 2 x, 3 x

Correct. The first output appears when b emits, using a's latest value, 2.

Why not the others?
  • A 1 x, 2 x, 3 x. Values sent before b's first value aren't replayed; only the latest is kept.
  • C 3 x. b's first value produces an output with a = 2 before a sends 3.
  • D 1 x, 3 x. combineLatest keeps only the latest value of a, which is 2 when b emits.

30-second answer

combineLatest waits until every upstream has emitted at least once, then emits a tuple of the latest value from each whenever any of them emits. It is ideal for state derived from several inputs, such as enabling a button when all form fields are valid.

Practise saying it · 30 s. No recording, just a timer

Explain combineLatest.

Say your answer out loud, then check which of these points you covered:

  • Latest of each
  • Needs a first value from all
  • Derived state

Deep dive

It emits nothing until every input has a first value.

Give CurrentValueSubject or @Published inputs so there is always a first value.

It finishes when all upstreams finish, and fails if any fails.

Up to four publishers can be combined directly.

Common mistakes

  • Expecting output before all inputs emit.
  • Using zip when you mean 'latest of each'.

Senior take & follow-ups

Seniors explain the first-value requirement and use it for derived state.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why doesn't my form validation emit at launch?

    Show hint

    One input hasn't emitted yet.

  2. combineLatest vs zip?

    Show hint

    Latest of each versus strict pairs.

Suggest a fix if something here is wrong or out of date.