1 minute read

Combine fundamentals for reactive Swift programming

Reactive programming gives iOS apps a way to describe values that arrive over time: taps, text edits, network responses, timers and location updates. Instead of scattering callback logic across view controllers, you model those events as streams, transform them and observe the result. The result is often easier to reason about, especially when several parts of an interface depend on the same event.

Apple’s Combine framework provides that model for reactive programming in Swift. It is available from iOS 13 onwards, works across Apple platforms and coexists with structured concurrency introduced in Swift 5.5. Combine is particularly useful for UIKit projects, but it also powers data binding in SwiftUI. For Australian developers working between Sydney, Melbourne and Brisbane, its value is practical: a clean event pipeline can reduce tangled state handling while preserving clear control of where work runs.

Why Combine belongs in modern iOS development

Combine arrived with iOS 13 in 2019 and turned a collection of familiar patterns—callbacks, delegates, notifications and observers—into a unified API. A publisher produces output, an operator changes that output, and a subscriber receives it. This event-driven design is valuable for code that reacts to several inputs, such as a search screen combining a query, selected filters and a network request.

The framework does not make imperative code illegal or automatically produce better architecture. It shines when there is a meaningful stream of values and when each transformation has a clear purpose. A one-off button action usually remains simpler as a normal target-action method. Knowing where Combine fits prevents a common beginner mistake: replacing every callback with a publisher when a direct method call would be clearer.

The iOS community is broader than one employer or platform. For readers interested in another regional perspective, the Kazakhstan iOS community shows how developers can share techniques while working across different markets and time zones. That cross-market perspective matters because app experiences must respect local conventions, including dates, currencies and expectations about error messages.

The mental model of publishers, subscribers and events

Publisher is a protocol that can emit zero, one or many values over time, followed by a completion event. Think of it as a typed event source. A subscriber attaches to that source with an operator such as map, filter or receive(on:, then ends with a terminal operator such as sink or assign. The associated Output and Failure types describe what the publisher publishes and how it can fail.

Publishers can be cold or hot. A cold publisher usually starts fresh work for each subscriber, much like a function that returns a sequence. A hot publisher shares an ongoing source, like a live radio broadcast. Just and Future are useful starting points for one value, while URLSession.DataTaskPublisher represents an asynchronous request. These examples cover very different lifetimes, so the publisher’s semantics matter more than its shape.

Subjects connect imperative code to a publisher. A PassthroughSubject forwards only values sent after a subscription exists. A CurrentValueSubject stores its latest value and sends that immediately to each new subscriber. After send, the values travel through the chain until one arrives at sink:

let greeting = Just("Hello")
    .map { $0.uppercased() }

let cancellable = greeting.sink { value in
    print(value)
}

The cancellable returned by sink is not disposable clutter. It is the subscription’s lifetime handle. If it is deallocated, the subscription ends and upstream work can stop. Store it in a property whose lifetime matches the consumer, or add it to a collection for a controller that owns several subscriptions.

Building a useful pipeline with operators

Operators are the heart of Combine. map transforms a value, filter rejects unwanted values, compactMap unwraps optionals and drops nil, and removeDuplicates suppresses repeated equal values. Chaining them creates declarative data flow. Each stage has one job, making a pipeline easier to inspect than nested completion handlers.

A practical search model might use a subject for user input, wait until typing pauses, remove repeated queries and replace an earlier request whenever a newer one starts:

final class SearchModel {
    private let query = PassthroughSubject<String, Never>()
    let suggestions: AnyPublisher<[String], Never>

    init(search: @escaping (String) -> AnyPublisher<[String], Never>) {
        suggestions = query
            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)
            .removeDuplicates()
            .map(search)
            .switchToLatest()
            .eraseToAnyPublisher()
    }

    func updateQuery(_ value: String) {
        query.send(value)
    }
}

switchToLatest cancels the previous inner publisher before forwarding the new one, which prevents an older network response from overwriting newer results. The AnyPublisher wrapper hides implementation details from the rest of the app. This is useful for a UIKit view model that exposes stable behaviour rather than exposing its internal subject.

Schedulers determine where time-based and delivery work happens. receive(on: DispatchQueue.main) is commonly used before updating UIKit controls because UI work must run on the main thread. It affects downstream delivery; it does not automatically move expensive upstream work off the thread that produced a value. Australia spans UTC+10, UTC+10:30 and UTC+11 depending on the city and date, with daylight-saving shifts in Sydney and Melbourne but not Brisbane. Scheduler choice should therefore follow the app’s actual timing needs, not a copy-and-paste recipe.

Comparing Combine with other reactive choices

Structured concurrency and Combine solve related problems in different ways. async and await are excellent for request-response work and sequential steps, while Combine is designed to compose ongoing event streams. They can work together: an asynchronous service can feed its output into a publisher, and a publisher can expose an asynchronous sequence. Choosing one tool for every task is less important than understanding the shape of the data flow.

Delegates remain a strong fit for one-to-one relationships, such as a picker telling its owner about a selected row. Notifications suit broad, loosely coupled events, although observers need filtering and do not receive a strongly typed value in the same way as a subscriber. The comparison below focuses on practical trade-offs rather than declaring one pattern the universal winner.

Approach Best fit Main benefit Main trade-off
Combine Continuous UI and asynchronous events Rich operators and cancellable chains More concepts can obscure simple flows
async and await Sequential asynchronous work Direct syntax and natural error propagation Combining parallel streams takes additional setup
Delegate One-to-one object communication Precise ownership and familiar UIKit pattern Callback plumbing grows as relationships multiply
NotificationCenter Cross-module broadcast events Loose coupling and easy posting Weak value typing and unrelated observer handling

For an Australian-facing product, format dates in the familiar day/month/year order, display prices in AUD and account for GST in purchase testing and reporting. Error wording should be direct as well: saying “no worries” after a failed payment may sound friendly in Australian conversation, but it can appear careless when money or data is at risk.

Recommendations for a durable Combine foundation

A productive learning path starts with the vocabulary of publishers, subscribers, operators, subjects and schedulers. Learn those concepts on a small, visible feature rather than by rewriting an entire app. A search field, a refresh button with a timer, or a form whose submit state depends on validation can demonstrate the full model without introducing unrelated architecture.

Several habits will prevent the most common Combine mistakes:

  • Give every publisher a clear lifetime and keep its AnyCancellable alongside the object that needs the values.
  • Keep UI updates on the main queue, and move network or file work deliberately to an appropriate background scheduler.
  • Use switchToLatest for replaceable work and merge when several ongoing sources should remain active.
  • Test debouncing, cancellation and failure handling with XCTest expectations rather than relying only on manual interaction.
  • Prefer a straightforward callback when the operation has one input and one output; reach for Combine when composition adds genuine clarity.

The aim is not to maximise the number of publishers in a project. It is to make event flow visible and disposable work controllable. A concise pipeline such as input, transformation, scheduling and observation can communicate intent more clearly than a long chain of mutable properties and nested callbacks.

Remember Combine’s core idea: model events as publishers, transform them with operators, observe them through subscribers, and tie each subscription to the lifetime of its consumer.

Updated: