Combine example with URLSession and assign value to a labels text

Combine Getting Started Guide

Learn Swift’s Combine framework through examples and sample code. A brief intro to publishers, operators, and subscribers.

Gary Tokman
6 min readMar 28, 2021

--

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.

  1. Create a new data task publisher to fetch data at a URL.
  2. Map on the response and get the Data via keypaths.
  3. Decode the response into a dictionary.
  4. CompactMap on the dictionary to the property results.
  5. Replace errors with an empty array (throwing away the error).
  6. Create a new publisher on the main queue.
  7. Assign the subscription input to the text property on UILable.
  8. 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.

An analogy of Combine concepts to Netflix
An analogy of Combine concepts to Netflix

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.

CHEATSHEET

--

--