Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 146 ยท Concurrency

Combine Basics

Learn Apple's Combine framework - publishers, subscribers, operators, subjects, @Published and cancellation - with runnable stand-ins you can try anywhere, plus how Combine compares to async/await.

Some values do not arrive once. A text field produces a new string on every keystroke, a sensor produces readings all day, a network connection delivers messages, a button emits a tap whenever the user presses it. Handling streams of values over time with nested callbacks gets messy quickly. Combine is Apple's framework for describing such streams declaratively: you connect a source of values, a chain of transformations, and a place that receives the result.

Combine ships with Apple's operating systems (iOS 13+, macOS 10.15+), so real Combine code cannot run on this site's Linux runner. That makes this lesson different from most: the real Combine listings are read-only, and every runnable example uses a tiny stand-in we wrote with closures and generics. The stand-ins are not Combine's types, but they follow the same model, so you learn the concepts here and recognise the real API later. You should be comfortable with closures, generics and the earlier async lessons first.

The three roles

Everything in Combine is one of three things:

  • A publisher describes a source of values over time. It may end with a completion (finished normally, or failed with an error). It does nothing until somebody subscribes.
  • An operator is a publisher built from another publisher; it transforms, filters, combines or delays what comes through (map, filter, debounce, merge...).
  • A subscriber receives values and completion. The common ones are sink (a closure that runs for each value) and assign (writes each value into a property).
flowchart LR
    P["Publisher<br/>source of values"] --> O1["filter"]
    O1 --> O2["map"]
    O2 --> S["Subscriber<br/>sink / assign"]
    S -. "returns" .-> C["AnyCancellable"]

Values flow downstream through operators; the subscriber gets a cancellable that ends the subscription.

Because publishers are lazy, creating a pipeline costs nothing and does no work. Work starts at the moment of subscription.

Real Combine in one look (read-only)

Here is the typical shape of a real pipeline. Do not worry about every symbol; the next sections rebuild the same ideas in runnable form.

Swift
// Read-only example: needs Combine and an Apple platform.
import Combine

var cancellables = Set<AnyCancellable>()

let numbers = [1, 2, 3, 4, 5, 6].publisher          // a Publisher of Int that finishes

numbers
    .filter { $0.isMultiple(of: 2) }
    .map { $0 * 10 }
    .sink(receiveCompletion: { print("completion:", $0) },
          receiveValue: { print("value:", $0) })
    .store(in: &cancellables)

// value: 20
// value: 40
// value: 60
// completion: finished

.sink returns an AnyCancellable. If you let it be deallocated, the subscription is cancelled, so you keep it: either in a variable or in a Set<AnyCancellable> with .store(in:). Forgetting this is the most common Combine bug: "my publisher never fires" is usually "I threw away the cancellable".

Subscription lifecycle

A subscription is a short conversation, not just a stream of values. The detail that sets Combine apart from plain callbacks is demand: a subscriber tells the publisher how many values it is ready for, so a slow subscriber cannot be flooded.

sequenceDiagram
    participant S as Subscriber
    participant P as Publisher
    S->>P: subscribe
    P-->>S: receive(subscription)
    S->>P: request(demand)
    P-->>S: receive(value) ...
    P-->>S: receive(completion)
    Note over S,P: cancel() at any time ends it

Subscribe, receive a subscription, request demand, get values, then a completion, unless you cancel first.

sink and assign request unlimited demand for you, so for everyday use you can ignore this. It matters when you write your own subscriber, or when you read the documentation of operators like buffer.

A stand-in you can run

The model fits in a few dozen lines. A stand-in Pub is a struct holding a function that, given a subscriber's callbacks, starts producing values. Operators wrap one Pub in another. sink provides the callbacks and returns a Token you can cancel.

Swift Publisher, operators and subscriber (stand-in types)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line proves that building the pipeline did no work. Each subscriber then gets its own run of the sequence: 20, 40, 60 and a completion, and a second subscriber that took prefix(2) receives 20, 40 and finishes early. The per-subscription state (seen) lives inside the start closure, which is why two subscribers do not interfere.

Subjects: pushing values in by hand

A publisher made from an array replays its data. Often you want to emit values yourself, for example when a delegate or button handler fires. Combine's PassthroughSubject and CurrentValueSubject do that; both are publishers you can also call send on.

  • PassthroughSubject<Output, Failure> forwards values to current subscribers and remembers nothing.
  • CurrentValueSubject<Output, Failure> stores the latest value, gives it to a new subscriber immediately, and exposes .value.

Here is a passthrough-style stand-in with cancellation:

Swift A subject and cancelling a subscription (stand-in types)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both subscribers see hello. After logger.cancel() only the counter receives bye, and the logger's completion never prints because it was cancelled. After the subject finishes, further sends are ignored, because a Combine publisher can complete at most once. Real subjects work the same way, with send(_:) for values and send(completion: .finished) for the end.

Operators you will use most

Real Combine has dozens of operators. These cover most code:

Category Operators What they do
Transform map, compactMap, flatMap, scan change each value, or build a running result
Filter filter, removeDuplicates, first, prefix, dropFirst decide what passes
Timing debounce, throttle, delay, timeout shape values in time
Combine merge, combineLatest, zip join several publishers into one
Errors catch, replaceError, retry, mapError recover from failures
Threads receive(on:), subscribe(on:) choose where work and delivery happen
Erase eraseToAnyPublisher() hide a long type behind AnyPublisher<Output, Failure>

Two ideas explain most of the surprises:

  • debounce waits until values stop for a while and then sends the last one. It is the standard way to avoid a search request on every keystroke.
  • combineLatest emits whenever any input emits, using the latest value of each, which is how you validate a form from several fields. zip instead pairs values one to one in order.

A search box in real Combine (read-only):

Swift
// Read-only example: needs Combine and an Apple platform.
import Combine
import Foundation

final class SearchModel {
    let query = CurrentValueSubject<String, Never>("")
    @Published private(set) var results: [String] = []
    private var cancellables = Set<AnyCancellable>()

    init(service: SearchService) {
        query
            .debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
            .removeDuplicates()
            .filter { $0.count >= 2 }
            .map { service.search($0) }                 // returns [String]
            .receive(on: DispatchQueue.main)
            .assign(to: &$results)                      // no cancellable needed
    }
}

assign(to: &$results) is the variant that writes into a @Published property and ties the subscription to the lifetime of the object. @Published itself is a property wrapper that creates a publisher: $results is its projected value, a publisher of that property's values, which SwiftUI used before Observation.

Operators as stand-ins: removeDuplicates and scan

Operators with memory keep state per subscription. Here are two more: removeDuplicates (only Equatable values) and scan, which carries an accumulator like reduce but emits every step.

Swift removeDuplicates and scan (stand-in types)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

removeDuplicates drops repeats only when they follow each other, so the final a still appears. The scan prints 5, 15, 35, 36: a running total. Notice the same pattern as before: the state variable (last, total) is created inside start, once per subscription.

Combine and async/await

Since Swift 5.5 you also have async/await and AsyncSequence, and Combine's role has narrowed. A rough guide:

Situation Prefer
One result later (a network call) async function
A stream consumed in order AsyncSequence / AsyncStream
UI state that changes @Observable models
Time-based operators (debounce, throttle), combining many streams, existing Combine APIs Combine (or the swift-async-algorithms package)

They interoperate: every Combine publisher has a .values property that is an AsyncSequence, and Future wraps a one-shot callback. A stand-in for the first idea, turning a push source into a for await loop with AsyncStream:

Swift From push to for-await (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because AsyncStream buffers, the values produced by run() before the loop starts are still delivered. This is the same bridge you would write with continuations (see continuations), and it is what Combine's .values does for you.

Combine is in maintenance mode: it still works, and many SwiftUI-era APIs expose publishers, but new Apple frameworks are designed around async/await and Observation. Learn Combine to read and maintain existing code and for its operators, but do not reach for it by default in a brand new project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a Combine publisher start producing values?

    Publishers are lazy. Creating a pipeline describes the work; subscribing starts it.
  2. 2. What happens if you do not keep the AnyCancellable returned by sink?

    AnyCancellable cancels its subscription in deinit, so store it in a property or a Set.
  3. 3. Which operator waits for values to pause and then sends only the latest?

    debounce suits search boxes: it turns a burst of keystrokes into a single value after a quiet period.
  4. 4. What is the difference between PassthroughSubject and CurrentValueSubject?

    A current-value subject has a value property and replays it on subscription.
  5. 5. In the stand-in pipeline, why do two subscribers to the same pipeline not interfere with each other?

    Subscribing calls start again, creating fresh state such as counters, which is also how real Combine publishers behave.

Summary

  • Combine models streams as publishers (sources), operators (transformations) and subscribers (sink, assign), connected lazily.
  • A subscription has a lifecycle with demand and ends with a completion or a cancel; keep the AnyCancellable or the subscription ends.
  • Subjects let you push values into a pipeline by hand; @Published turns a property into a publisher.
  • Frequently used operators: map, filter, removeDuplicates, debounce, combineLatest, merge, flatMap, catch, receive(on:).
  • Real Combine runs only on Apple platforms, so this page used stand-in types with the same structure.
  • For new code prefer async/await, AsyncSequence and Observation, and bridge with .values or AsyncStream when needed.

Next: Text Processing