Combine Getting Started Guide
Learn Swift’s Combine framework through examples and sample code. A brief intro to publishers, operators, and subscribers.
What is Combine?
In short, Combine enables subscribing to output or values over time with a declarative API. For example, if you’re making a network request to fetch JSON.
Notice how Combine is built into url session, you’ll see it throughout Apple’s API ecosystem i.e notification center, timers.
- Create a new data task publisher to fetch data at a URL.
- Map on the response and get the
- Decode the response into a dictionary.
- CompactMap on the dictionary to the property results.
- Replace errors with an empty array (throwing away the error).
- Create a new publisher on the main queue.
- Assign the subscription input to the text property on
- Cancel the subscription and release it from memory.
We’ve achieved a composable chain of operations in a URL as an input and delivered the output to subscribers in a UI consumable model.
Another way to remember this pipeline is with an analogy using Netflix. Netflix publishes movies and tv shows to their servers. Then some operations are run to make them appear in an app. Finally, you subscribe to Netflix to access the movies, and when you no longer want to use Netflix, you cancel your subscription.
Combine has four main parts, publishers, operators, subscribers, and cancellable. Get familiar with these four terms because they are the foundation of the framework. Here is a cheatsheet of the terminology.