With Combine, why does a flight search that flatMaps each query into a request stop for good after one failed request and show stale results, and how do you fix both?
answer
- a failure is a completion
- catch swaps the upstream, then finishes
- handle errors inside the per-query publisher
- flatMap keeps every request subscribed
- map, then switchToLatest
basics
~20 sA failed inner publisher fails the whole flatMap stream, and a catch or replaceError at the end only sends a fallback and finishes. Handle errors inside each query's publisher, then use map plus switchToLatest so a new query cancels the previous request.
solid answer
~50 sIn Combine a failure is a terminal completion, and Apple's `flatMap` documentation says failure of an inner publisher causes the overall stream to fail. A `catch { _ in Just([]) }` at the end of the chain doesn't resume the search: it replaces the failed upstream with `Just`, which sends one value and finishes, and `replaceError(with:)` likewise sends its element and finishes. So the first bad response silently ends every later search. Handle errors per query instead, inside the publisher built for that query: `retry(1)` for a transient failure, then `catch` into an empty or error state, which makes that inner publisher's `Failure` `Never`. The stale results come from `flatMap` too: it stays subscribed to every inner publisher until each completes and merges their values, so a slow response for 'lo' can land after the one for 'lon'. Replace it with `map` into the request publisher followed by `switchToLatest()`, which cancels the previous inner subscription when a new one arrives.
code
swift · 28 linesimport Combine
import Foundation
struct FlightOffer: Decodable { let number: String }
final class FlightResultsModel {
@Published var query = ""
@Published private(set) var offers: [FlightOffer] = []
init(session: URLSession = .shared) {
$query
.debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
.removeDuplicates()
.map { query -> AnyPublisher<[FlightOffer], Never> in
var parts = URLComponents(string: "https://api.example.com/offers")!
parts.queryItems = [URLQueryItem(name: "q", value: query)]
return session.dataTaskPublisher(for: parts.url!)
.retry(1) // one more attempt
.map(\.data)
.decode(type: [FlightOffer].self, decoder: JSONDecoder())
.catch { _ in Just([]) } // this request ends, the pipeline lives
.eraseToAnyPublisher()
}
.switchToLatest() // cancels the previous request
.receive(on: DispatchQueue.main)
.assign(to: &$offers)
}
}go deeper
Recall that an error ends a Combine pipeline, and that catch and replaceError recover with a fallback rather than resuming the original stream.
Explain that inner failures fail flatMap's whole stream, what catch, replaceError and retry each do, and why handling the error per request keeps the outer stream alive.
Diagnose a search that went silent or flickered back to old results, then restructure it: per-request retry and catch, map plus switchToLatest, one hop to the main queue.
Turn this into a review rule for every input-driven pipeline: errors handled inside the per-event publisher, and latest-wins switching wherever stale results would mislead.
## Why one failure ends everything Every Combine publisher declares a `Failure` type, and a failure is delivered as a **completion**: after it, the subscription is over and no more values flow. A search pipeline built as `$query.flatMap { search($0) }` has an outer publisher that never fails and inner request publishers that can. Here is what happens on the first error: 1. A query produces a request publisher, and `flatMap` subscribes to it. 2. The request fails. Apple's documentation for `flatMap(maxPublishers:_:)` is explicit: successful completion of an inner publisher does not complete the stream, but **failure of an inner publisher causes the overall stream to fail**. 3. The failure travels downstream, the sink receives `.failure`, and the subscription to `$query` is cancelled. 4. The user keeps typing; nothing listens any more. Adding an error handler at the **end** of the chain changes the symptom, not the outcome. ## What the error operators actually do | Operator | On an upstream failure | Afterwards | |---|---|---| | `catch(_:)` | Replaces the failed upstream with the publisher you return | Continues only as long as that replacement does; `Just` sends one value and finishes | | `replaceError(with:)` | Sends the replacement element | Finishes normally | | `retry(_:)` | Re-subscribes to the upstream, up to the given number of times | Fails with the last error once retries run out | Apple's `replaceError(with:)` page frames the choice the same way: use it to send a single replacement element and end the stream, and `catch` to supply a publisher that keeps providing elements. At the end of a search pipeline, both end the search. ## Keep the outer pipeline alive The rule is to handle the error **where it happens, inside the publisher built for one query**: - `dataTaskPublisher(for:)` makes the request, `retry(1)` re-subscribes once, which issues a fresh request, and `decode` turns data into model values. - `catch { _ in Just([]) }`, or a mapping into a result or error-state enum, ends **that request** with a fallback. - The inner publisher's `Failure` is now `Never`, so nothing can fail the outer stream. ## flatMap versus map plus switchToLatest The second bug is ordering. `flatMap` stays subscribed to **every** inner publisher until each one completes, and merges whatever they emit. If 'lo' is slow and 'lon' is fast, the screen shows results for 'lon' and then overwrites them with results for 'lo'. Options: - **`map` + `switchToLatest()`**: `map` produces a publisher per query and `switchToLatest()` subscribes to the newest one. Apple's documentation says that when it receives a new publisher it **cancels its previous subscription**, which also stops the earlier request doing work. It also notes that a request can finish before it can be cancelled, so old results may still arrive, but only if they come in before the newer query's publisher does. - **`flatMap(maxPublishers: .max(1))`** limits flatMap to one inner subscription at a time. That is not "latest wins": with a `PassthroughSubject` upstream, queries sent while a request is in flight are dropped, because the subject drops values when demand is zero. - Since iOS 14, `switchToLatest()` and `flatMap` have overloads for a `Never`-failing upstream with failing inner publishers, which saves a `setFailureType(to:)` call. ## Putting it together The snippet debounces the field, removes duplicates, builds one request per query with `retry` and an inner `catch`, switches to the latest request, then delivers on the main queue into an `@Published` property with `assign(to:)`, so there is also no token to manage. ## Showing errors without failing Returning an empty array from `catch` keeps the pipeline alive but hides the failure from the user. A sturdier shape is to make the inner publisher emit **state** rather than raw results: - `map { .loaded($0) }` turns results into a case of an enum such as `loading`, `loaded` and `failed`. - `catch { Just(.failed($0)) }` turns the error into a value of the same enum. - `prepend(.loading)` can show a spinner as each request starts. The screen renders whatever case arrives, the outer stream still has `Failure == Never`, and the next query starts from a clean state. ## Review checklist - Is any `catch` or `replaceError` placed after a `flatMap` or `switchToLatest` on a long-lived input? It will end the input. - Does each inner publisher end with `Failure == Never`? - Is `flatMap` used where only the latest result should win? - Is `retry` applied to the request publisher rather than somewhere that never fails? - Is there exactly one `receive(on: DispatchQueue.main)` before UI state?
- Where should retry go in this pipeline, and what does it actually repeat?On the inner request publisher, before `catch`. `retry(_:)` re-subscribes to its upstream after a failure, and re-subscribing to a `dataTaskPublisher` issues a new request. Placed directly on `$query`, it does nothing, because that publisher never fails; the failures happen in the request publishers further down the chain.
- How do you show an error message without ending the pipeline?Make the inner publisher emit a state instead of failing, for example `map { .loaded($0) }` followed by `catch { Just(.failed($0)) }` into an enum the screen renders. The outer stream still never fails, each query ends with either results or an error state, and the next query starts cleanly.
- Why might results for an older query still appear after switchToLatest?`switchToLatest()` cancels the previous inner subscription when a new inner publisher arrives, but a response that has already been delivered cannot be taken back. Apple's documentation notes that earlier requests may finish before they can be cancelled; their values arrive before the operator switches to the newer publisher, so the screen still ends on the latest query.
- catch at the end of the chain keeps the search pipeline running
- replaceError(with:) swaps the error for a value and keeps listening
- A failed inner publisher ends only that request inside flatMap
- flatMap(maxPublishers: .max(1)) gives latest-query-wins behaviour
- retry placed directly on $query retries the failed requests
Assumes the iOS 27.1 SDK with an iOS 17 deployment target; assign(to:) and the switchToLatest and flatMap overloads for a Never-failing upstream are iOS 14, so none needs an availability check.