skip to content

In a SwiftUI stock-quote screen, how do you reload when the selected symbol changes and stop polling when the screen disappears?

level: seniorimportance: should knowfreq 55%

answer

  1. one modifier, an Equatable id
  2. cancel and restart on a new value
  3. sleep throws when cancelled
  4. check cancellation before writing state

basics

~20 s

Attach task(id: symbol) with a polling loop: SwiftUI starts it before the screen appears, cancels and restarts it when symbol changes, and cancels it after the screen disappears, provided the loop's sleep and requests honour cancellation.

solid answer

~40 s

`.task(id: symbol) { ... }` replaces three hand-written pieces: `onAppear` to start, `onChange` to restart and `onDisappear` to stop. SwiftUI compares the new `id` with the old one using `==`; when they differ it cancels the running task and starts a fresh one, and when the view is removed it cancels the task. Inside, loop while `!Task.isCancelled`, fetch, then `try await Task.sleep(for:)`, which throws on cancellation and ends the loop. Cancellation is cooperative, so a request that ignores it can still return late: call `Task.checkCancellation()` after the `await` before assigning, or a slow reply for the old symbol overwrites the new one. And don't report cancellation as a failure.

code

swift · 47 lines
swift
import SwiftUI

struct Quote: Sendable {
    let symbol: String
    let price: Double
}

protocol QuoteService: Sendable {
    func quote(for symbol: String) async throws -> Quote
}

struct QuoteScreen: View {
    let symbol: String
    let service: any QuoteService
    @State private var quote: Quote?
    @State private var stale = false

    var body: some View {
        VStack {
            if let quote {
                Text(quote.price, format: .currency(code: "USD"))
            } else {
                ProgressView()
            }
            if stale { Text("Prices may be out of date.") }
        }
        .task(id: symbol) {
            quote = nil
            while !Task.isCancelled {
                do {
                    let latest = try await service.quote(for: symbol)
                    try Task.checkCancellation() // a late reply for an old symbol stops here
                    quote = latest
                    stale = false
                } catch {
                    if Task.isCancelled { break }
                    stale = true
                }
                do {
                    try await Task.sleep(for: .seconds(5))
                } catch {
                    break // cancelled: the symbol changed or the screen went away
                }
            }
        }
    }
}

go deeper

for a junior

Recall that task(id:) starts work when the view appears and starts it again when the id value changes.

for a middle

Explain the Equatable comparison behind the restart, and how Task.sleep and cancellation end a polling loop.

for a senior

Demonstrate the stale-reply race, the cancellation check that closes it, and how a badly chosen id restarts work on every update.

for a principal

Argue that one task(id:) per input set replaces hand-rolled start, restart and stop hooks, and make it the reviewed pattern for polling screens.

## The hand-written version and its races A stock-quote screen has three lifecycle needs: load when shown, reload when the selected symbol changes, and stop polling when the screen goes away. Written with separate hooks it looks like this: - `onAppear` starts a `Task` that loads and then polls on a timer. - `onChange(of: symbol)` starts another `Task` for the new symbol. - `onDisappear` cancels whatever handles were stored. Every piece is a chance to get it wrong. Forget to cancel the old task in `onChange` and two loops poll at once. Store only the latest handle and an earlier loop leaks. And a slow reply for the old symbol can land after the new one, so the screen shows the wrong price under the right title. ## How task(id:) behaves `task(id:_:)` (in the iOS 27 SDK, `task(id:name:priority:file:line:_:)`) folds all three into one modifier. Apple's documentation states it: 1. Runs the action as an async task **before the view appears**, like the plain `task` modifier. 2. Tests whether a new `id` value **equals** the previous one, which is why `id` must conform to `Equatable`; when it differs, SwiftUI **cancels the running task and creates a new one**. 3. Cancels the task if it has not finished when the view is removed or changes identity. So `.task(id: symbol)` gives you load-on-show, restart-on-change and stop-on-disappear with no stored handles. ## The polling loop The code example in this question shows the shape: loop while `!Task.isCancelled`, fetch, then `try await Task.sleep(for: .seconds(5))`. `Task.sleep` throws when the task is cancelled, so a symbol change or a disappearance ends the wait at once and the `catch` breaks the loop. ## Tracing the code example Walking through the example once for each way the task can end makes the guard logic concrete: 1. **The symbol changes while a request is in flight.** SwiftUI cancels the task. A request that honours cancellation throws, and the `catch` sees `Task.isCancelled` and breaks without marking prices stale. A request that ignores it returns, and `Task.checkCancellation()` throws before `quote` is assigned. 2. **The symbol changes during the sleep.** `Task.sleep(for:)` throws, the second `catch` breaks, and SwiftUI has already started a new task for the new symbol. 3. **The screen disappears.** The same two paths apply, and nothing is left running. 4. **A real network failure.** `Task.isCancelled` is false, so `stale` becomes `true`, the loop sleeps and tries again on the next pass. ## Cancellation is still cooperative SwiftUI cancelling the old task does not stop it in its tracks. A request that ignores cancellation can still return, and the old closure would then assign its quote over the new symbol's. Two habits close the gap: - After every `await` whose result you are about to write into state, check `Task.isCancelled` or call `Task.checkCancellation()`. - In the `catch`, treat cancellation as a normal exit: do not mark the data stale or show an error because the user picked another symbol. ## Choosing the id | id choice | Effect | |---|---| | `symbol` | Restarts when the user picks another symbol | | A small `Equatable` struct of symbol and interval | Restarts when either input changes | | `Date()` or `UUID()` computed in `body` | Restarts on every body evaluation, which is a bug | | A large model object | Restarts on any change `==` detects, often more than intended | When the work depends on several inputs, combine them into one `Equatable` struct rather than chaining several modifiers. ## What can still go wrong 1. **The id changes too often.** If the value is recomputed and differs on every update, the task is cancelled and restarted constantly and may never finish a load. 2. **The screen never disappears.** Moving the app to the background does not make the view disappear, so the task is not cancelled by that alone; app-level scene phase and background execution are separate subjects. 3. **The loop swallows cancellation.** A `try?` around `Task.sleep` discards the cancellation error; the loop then relies on its `while !Task.isCancelled` check to exit, so keep that check. 4. **State resets surprise users.** Clearing `quote` at the top of the closure shows a spinner on every symbol change; that is a product choice, so make it deliberately.

  • What happens if the user switches symbols faster than a request completes?
    Each change cancels the previous task and starts a new one, so only the latest closure keeps running. Requests that honour cancellation end early; one that ignores it returns, but the `Task.checkCancellation()` after the `await` throws before the old quote is written. The screen ends up showing only the latest symbol's data.
  • The work depends on the symbol and a refresh interval; how do you restart on either?
    Make one `Equatable` struct holding both values and pass it as the `id`. Any change to either field makes the new value unequal to the old one, so SwiftUI cancels and restarts the task. Chaining two `task(id:)` modifiers would run two independent loops instead.

  • task(id:) only runs when the id changes, not when the view first appears.
  • Once SwiftUI cancels the old task, its late reply can never overwrite the new state.
  • Any value can be the id, whether or not it conforms to Equatable.
  • Passing Date() as the id makes the task refresh on a schedule.
  • You still need onDisappear to stop a task(id:) polling loop.