Skip to content
DeveloperMemos

Using Combine's combineLatest

Combine, iOS, Swift1 min read

One of the most useful operators in the Combine framework is combineLatest. This operator combines the latest values from multiple publishers into a new publisher, emitting a new value whenever any of the input publishers produce a new value. The resulting publisher will only emit a new value when all of the input publishers have emitted at least one value.

To use combineLatest, you need to import the Combine framework into your project. Here's an example of how to import Combine in Swift:

1import Combine

Once you've imported Combine, you can use the combineLatest operator to combine the latest values from multiple publishers. The basic syntax of combineLatest is as follows:

1func combineLatest<P, Q>(_ publisher1: P, _ publisher2: Q) -> Publishers.CombineLatest<P, Q>
2 where P: Publisher, Q: Publisher, P.Failure == Q.Failure

The combineLatest function takes two publishers as input parameters and returns a new CombineLatest publisher. You can also combine more than two publishers by chaining multiple combineLatest operators.

Let's take a look at a practical example. Suppose you have two publishers: usernamePublisher and passwordPublisher, which emit the latest values of a username and password respectively. You want to perform some validation logic whenever either of these values changes. Here's how you can use combineLatest to achieve that:

1import Combine
2
3let usernamePublisher = PassthroughSubject<String, Never>()
4let passwordPublisher = PassthroughSubject<String, Never>()
5
6let credentialsValidator = usernamePublisher.combineLatest(passwordPublisher)
7 .sink { (username, password) in
8 // Perform validation logic here
9 // ...
10 }

In the above example, we create two PassthroughSubject publishers: usernamePublisher and passwordPublisher. We then use combineLatest to combine the latest values from both publishers into a single CombineLatest publisher. Finally, we subscribe to the combined publisher using the sink operator to perform the validation logic whenever the username or password changes.

In Summary

  • combineLatest combines the latest values from multiple publishers.
  • It emits a new value whenever any of the input publishers produce a new value.
  • The resulting publisher emits a new value only when all of the input publishers have emitted at least one value.
  • Use combineLatest to synchronize and react to changes in multiple publishers.