Skip to content
Commitwise
Menu
iOS Development

Combine and moving to async/await

Read and write Combine pipelines with publishers, operators and subscriptions, avoid the classic bugs (lost subscriptions, stale results, a pipeline killed by one error, retain cycles), bridge Combine and async/await, and decide what to migrate to Observation and AsyncSequence.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The search screen in a five-year-old app is one long Combine chain: $query, debounce, removeDuplicates, flatMap, receive(on:), sink. It mostly works. But after one network error, typing does nothing until the screen is reopened. Fast typists sometimes see results for an older query. And a new teammate asks whether all of this should just be rewritten with async/await.

Combine is Apple’s framework for values that change over time: you describe a pipeline once, and values flow through it. New SwiftUI code mostly uses Observation and async/await instead, but Combine is still in most existing codebases, and senior interviews still ask about it. This lesson teaches you to read it, fix it, and migrate it when that pays off.

New to some of these? Open what you need, or skip ahead.

Basics:What is a closure?

A closure is a block of code you can pass around and run later, like { value in print(value) }. In Combine, you give closures to operators (map { $0 * 2 }) and to the subscriber at the end (sink { … }). A closure that uses self keeps self alive while the closure exists. See retain cycleRetain cycleTwo or more objects holding strong references to each other, so none of them is ever freed.Open in glossary →.

Basics:What is ObservableObject and @Published?

Before iOS 17’s @Observable, SwiftUI view models were classes conforming to ObservableObject, with properties marked @Published. When a published property changes, SwiftUI redraws the views that use the object. $query (with a dollar sign) gives you a publisher for that property: a stream of its values.

Part Not started

Publishers, operators and subscriptions

Think of a pipeline as a water pipe with filters. The publisherPublisher (Combine)A Combine type that emits values over time, then finishes or fails, to subscribers that request them.Open in glossary → is the tap: it sends values. Operators are filters along the pipe: change each value (map), drop some (filter), wait for a pause (debounce). The subscriber at the end is the glass: sink runs a closure for each value that arrives.

A publisher can send any number of values, and then it may end: either it finishes normally or it fails with an error. After that, nothing more comes through.

One rule surprises everyone at first: sink returns an AnyCancellable, a ticket for the subscription. When the ticket is thrown away, the subscription is cancelled. So you keep it, usually in a Set<AnyCancellable> on the object.

A Publisher has Output and Failure types and emits zero or more values followed by at most one completion (.finished or .failure). Subscribers request demand (sink and assign request .unlimited), which is how Combine models backpressure. Most publishers are cold (each subscription starts its own work: two subscribers to a dataTaskPublisher make two requests; share() or multicast makes it hot), while subjects (PassthroughSubject, CurrentValueSubject) and @Published are hot. @Published emits in willSet, before the property changes. A completed stream never emits again, which is why errors must be handled inside flatMap/map+switchToLatest rather than at the end of a long-lived pipeline. Threading: operators run on whatever thread the upstream emits on; receive(on:) moves downstream delivery, subscribe(on:) moves subscription and upstream work.

import Combine

@MainActor
final class SearchViewModel: ObservableObject {
    @Published var query = ""
    @Published private(set) var results: [Product] = []

    private var cancellables = Set<AnyCancellable>()

    init(api: ProductAPI) {
        $query
            .map { $0.trimmingCharacters(in: .whitespaces) }
            .removeDuplicates()                                   // "sh", "sh" → one request
            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)   // wait for a pause in typing
            .filter { $0.count >= 2 }
            .map { query in
                api.search(query)                                 // AnyPublisher<[Product], Error>
                    .replaceError(with: [])                       // handle errors per request
            }
            .switchToLatest()                                     // only the newest query's results
            .receive(on: DispatchQueue.main)
            .assign(to: &$results)                                // lives as long as self, no cycle
    }
}

struct ProductAPI {
    func search(_ query: String) -> AnyPublisher<[Product], Error> {
        var components = URLComponents(string: "https://api.example.com/search")!
        components.queryItems = [URLQueryItem(name: "q", value: query)]
        return URLSession.shared.dataTaskPublisher(for: components.url!)
            .map(\.data)
            .decode(type: [Product].self, decoder: JSONDecoder())
            .eraseToAnyPublisher()
    }
}

Reading it top to bottom:

  1. $query sends the text every time the user types.
  2. removeDuplicates skips a value equal to the previous one; debounce waits until typing pauses for 300 ms; filter ignores one-letter queries.
  3. map turns each query into a network request (itself a publisher). If the request fails, replaceError turns the error into an empty list, for that one request only.
  4. switchToLatest listens only to the newest request, so results for an old query can’t overwrite newer ones.
  5. assign(to: &$results) writes each result into results. This form manages its own subscription, so no AnyCancellable is needed here.
Spot the bugThe timer that never ticks

Tap the line with the bug.

final class ClockViewModel: ObservableObject {
    @Published var now = Date()

    func start() {
        Timer.publish(every: 1, on: .main, in: .common)
            .autoconnect()
            .sink { [weak self] date in
                self?.now = date
            }
    }
}

Predict the output

A view model has @Published var count = 0, and in init: $count.sink { [weak self] value in print(value, self?.count ?? -1) }.store(in: &cancellables). Then count = 5 runs. What is printed after "0 0" from the subscription?

Practice: a form that enables its button

combineLatest joins publishers: it emits whenever any of them changes, with the latest value of each. That’s perfect for form validation.

final class SignUpViewModel: ObservableObject {
    @Published var email = ""
    @Published var password = ""
    @Published private(set) var canSubmit = false

    init() {
        $email.combineLatest($password)
            .map { email, password in
                email.contains("@") && password.count >= 8
            }
            .removeDuplicates()
            .assign(to: &$canSubmit)
    }
}
Exercisemedium

Show a loading indicator

Add @Published private(set) var isLoading = false to the search view model: true while a request is running, false when its results (or the error) arrive.

›

handleEvents(receiveOutput:) runs a side effect when a value passes through, without changing it. Where in the pipeline does a request start?

SolutionTry it yourself first

Set it to true when a query passes the filter, and back to false when results arrive:

$query
    .map { $0.trimmingCharacters(in: .whitespaces) }
    .removeDuplicates()
    .debounce(for: .milliseconds(300), scheduler: RunLoop.main)
    .filter { $0.count >= 2 }
    .handleEvents(receiveOutput: { [weak self] _ in self?.isLoading = true })
    .map { api.search($0).replaceError(with: []) }
    .switchToLatest()
    .receive(on: DispatchQueue.main)
    .sink { [weak self] products in
        self?.isLoading = false
        self?.results = products
    }
    .store(in: &cancellables)

sink replaces assign here because two properties change; [weak self] avoids a cycle, since self stores the subscription.

Operators interviewers ask about

OperatorBehavior
flatMapSubscribes to every inner publisher; results from all of them interleave (bounded by maxPublishers).
map + switchToLatestCancels the previous inner publisher when a new one arrives. Right for search.
combineLatestEmits the latest of each once all have emitted; on any change.
zipPairs values by index; waits for both.
mergeInterleaves same-typed publishers.
debounce / throttleEmit after a quiet period / at most once per interval.
share()One upstream subscription for many subscribers (hot).
catch / replaceErrorReplace a failure with another publisher / value; the upstream is still finished.

assign(to: \.results, on: self) retains self strongly through the returned AnyCancellable; stored in self.cancellables, that’s a retain cycle. assign(to: &$results) (iOS 14+) ties the subscription to the @Published property instead and has no cycle.

  • Publisher → operators → subscriber; values then at most one completion. Demand-based backpressure; sink/assign request unlimited.
  • AnyCancellable owns the subscription: dropped = cancelled. Store it (store(in:)) or use assign(to: &$prop).
  • Cold vs hot: dataTaskPublisher per subscriber; share() to multicast. @Published emits in willSet.
  • Search: removeDuplicates → debounce → map { request.catch… } → switchToLatest → receive(on: main).
  • flatMap interleaves all inner results; switchToLatest cancels the old one. assign(to:on: self) retains self.

Check this part

  1. A sink’s AnyCancellable isn’t stored anywhere. What happens?

  2. What does debounce(for: .milliseconds(300)) do to a stream of keystrokes?

  3. Search uses flatMap for requests. A slow request for "sw" returns after the one for "swift". What does the user see?

  4. Which subscription creates a retain cycle when stored in self.cancellables?

A publisher emits values, then finishes or fails; operators transform them; a subscriber (sink, assign) requests them. A subscription lives only as long as its AnyCancellable, so store it. Search pipelines use removeDuplicates, debounce, then map to a request plus switchToLatest so older results are dropped, and handle errors inside that inner publisher so one failure doesn't end the whole stream. @Published emits on willSet.

Part Not started

Errors, bridging and migrating

The search bug from the start of the lesson has a simple cause: an error ends a publisher forever. If the network request’s error reaches the main pipeline, the whole pipeline finishes, and $query changes go nowhere. That’s why the example handled errors inside the map, on each request.

Today, new SwiftUI screens often skip Combine. The same search with @Observable and async/await is shorter, and SwiftUI’s .task(id:) does the hard parts: it starts the work when the id changes and cancels the previous one, so old results can’t win.

Combine and Swift concurrency interoperate in both directions: any publisher exposes .values, an AsyncSequence you can for await over (a throwing one when Failure is an Error), and callback or async work becomes a publisher with Future or a Task feeding a subject. Apple’s direction is Observation plus async/await and AsyncSequence; Combine is stable but hasn’t gained features since 2021, and @Published doesn’t work inside @Observable types. The replacements: .task(id:) for “restart on change” (with Task.sleep as a debounce), AsyncStream for event streams, and swift-async-algorithms for debounce, throttle, combineLatest, merge and zip on async sequences. Migration is per screen and per boundary: new view models use @Observable; existing publishers are consumed with .values; long operator chains with several timing-sensitive inputs can stay in Combine until there’s a reason to touch them.

@Observable @MainActor
final class SearchModel {
    var query = ""
    private(set) var results: [Product] = []
    private let api: ProductAPI

    init(api: ProductAPI) { self.api = api }

    func search() async {
        let query = query.trimmingCharacters(in: .whitespaces)
        guard query.count >= 2 else { results = []; return }
        do {
            try await Task.sleep(for: .milliseconds(300))      // debounce: cancelled if the user keeps typing
            results = try await api.search(query)              // async version of the API
        } catch is CancellationError {
            // a newer query replaced this one
        } catch {
            results = []                                       // this request failed; the next one still runs
        }
    }
}

struct SearchView: View {
    @State private var model = SearchModel(api: ProductAPI())

    var body: some View {
        List(model.results) { ProductRow(product: $0) }
            .searchable(text: $model.query)
            .task(id: model.query) { await model.search() }    // cancels the previous run on every change
    }
}

// Bridging: consume an existing publisher from async code
for await isOnline in reachability.$isOnline.values {
    if isOnline { await syncPendingChanges() }
}
  • .task(id: model.query) runs search() when the screen appears and again whenever query changes, cancelling the run before it.
  • Task.sleep throws CancellationError if the task is cancelled while sleeping, so a fast typist only causes one request: the old runs stop at the sleep.
  • Errors are caught inside search(), one call at a time, so a failed request doesn’t break the next one.
  • .values turns any publisher into something you can loop over with for await.

Production puzzles

Predict the output

A pipeline: $query.debounce(...).flatMap { api.search($0) }.receive(on: DispatchQueue.main).sink(receiveCompletion: { print("done:", $0) }, receiveValue: { self.results = $0 }). The network drops once and search fails with URLError(.notConnectedToInternet). The connection comes back and the user types again. What happens?

Spot the bugA cycle through a stored subscription

Tap the line with the bug.

final class ProfileViewModel: ObservableObject {
    @Published private(set) var name = ""
    private var cancellables = Set<AnyCancellable>()

    init(store: UserStore) {
        store.$user
            .map(\.displayName)
            .assign(to: \.name, on: self)
            .store(in: &cancellables)
    }
}

Exercisehard

Migrate a view model

A UIKit + Combine screen: ProductViewModel: ObservableObject with @Published product, @Published isFavorite, a combineLatest of product and a FavoritesService.$ids publisher, and a PassthroughSubject<Void, Never> for “retry”. You’re moving the screen to SwiftUI. What’s your plan, and what do you keep in Combine?

›

Separate what the screen owns (state, actions) from what it observes from shared services, which other Combine code may still use.

SolutionTry it yourself first
  • The view model becomes @Observable: product and isFavorite are plain properties; “retry” becomes a method func retry() async instead of a subject.
  • Loading moves to func load() async, started from .task and re-run by retry().
  • The shared FavoritesService keeps its @Published ids for now, because other screens subscribe to it. The new model consumes it with for await ids in service.$ids.values in a task tied to the view (.task { await model.observeFavorites() }), computing isFavorite from it, so SwiftUI cancels the loop when the view disappears.
  • Later, migrate FavoritesService itself (an @Observable service or an AsyncStream) once its other subscribers move.
  • Tests: async tests call load() and retry() directly; no scheduler or expectation juggling.
Exercisemedium

Bridge a callback API

An old SDK has func fetchUser(id: String, completion: @escaping (Result<User, Error>) -> Void). Write an async throws version you can call from the search model.

›

withCheckedThrowingContinuation pauses an async function until you call resume exactly once.

SolutionTry it yourself first
extension LegacySDK {
    func user(id: String) async throws -> User {
        try await withCheckedThrowingContinuation { continuation in
            fetchUser(id: id) { result in
                continuation.resume(with: result)   // resumes exactly once, with the value or the error
            }
        }
    }
}

resume(with:) takes the Result directly. Resuming twice crashes, and never resuming leaves the caller waiting forever, so make sure the SDK always calls the completion exactly once.

  • A failure terminates the stream for good: catch per inner publisher; long-lived pipelines should have Failure == Never.
  • Combine → async: publisher.values; callbacks → async: checked continuations; async → Combine: Future or a Task sending into a subject.
  • New SwiftUI: @Observable + async methods + .task(id:) (auto-cancels; Task.sleep debounce). @Published doesn’t work in @Observable types.
  • Timing operators over async sequences: swift-async-algorithms (debounce, throttle, combineLatest, merge).
  • Migrate per screen; keep shared publishers until their subscribers move.

Check this part

  1. A request inside a Combine search pipeline fails and the error isn’t caught. What happens to later searches?

  2. What does .task(id: query) do when query changes?

  3. How do you consume an existing @Published property from async code?

  4. Which pipeline should have Failure == Never?

Errors end a Combine stream for good, so catch them per request. Bridge Combine to async/await with publisher.values (an AsyncSequence) and wrap callback APIs with continuations. New SwiftUI code uses @Observable with async functions and .task(id:), which cancels the previous work automatically. Keep Combine where timing operators across several streams make it clearer, or use swift-async-algorithms; migrate screen by screen.

Key takeaways

  • A publisher sends values through operators to a subscriber; keep the AnyCancellable.
  • debounce, removeDuplicates and switchToLatest make a good search.
  • Catch errors on each request, or one failure ends the pipeline.
  • New SwiftUI code can use @Observable, async functions and .task(id:) instead.
  • Know completion semantics, demand, hot vs cold, and @Published willSet timing.
  • switchToLatest over flatMap for “latest wins”; Failure == Never for long-lived pipelines.
  • Avoid assign(to:on: self) cycles; prefer assign(to: &$prop).
  • Bridge with .values and continuations; migrate screen by screen toward Observation and async sequences.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.