skip to content

In SwiftUI, how does refreshable drive pull to refresh on a List, and why does wrapping its work in a Task break it?

level: middleimportance: should knowfreq 50%

answer

  1. a value in the environment
  2. the list detects a RefreshAction
  3. indicator lasts while the handler runs
  4. fire-and-forget returns at once

basics

~20 s

refreshable(action:) stores a RefreshAction in the environment; a List on iOS offers pull to refresh and keeps its indicator visible while the async handler runs, so wrapping the work in Task { } returns at once and hides it early.

solid answer

~40 s

`.refreshable { await model.reload() }` stores a `RefreshAction` in the `refresh` environment value. Views that find one, such as `List` on iOS and iPadOS, offer the pull-to-refresh gesture; when the person pulls, the list calls the handler and, per Apple's documentation, keeps the progress indicator visible for the duration of the refresh. That duration is the lifetime of the async handler, so the work must be awaited inside it. Writing `Task { await model.reload() }` inside returns immediately: the indicator disappears before data arrives, and repeated pulls can start overlapping loads. As an environment value it applies to the views beneath, and custom views can read `@Environment(\.refresh)` and call it with `await`. The handler inherits the view's main actor, like `task`.

code

swift · 24 lines
swift
import SwiftUI
import Observation

@MainActor @Observable
final class WatchlistModel {
    var symbols: [String] = []

    func reload() async {
        // Fetch the latest symbols and assign them to `symbols`.
    }
}

struct WatchlistScreen: View {
    @State private var model = WatchlistModel()

    var body: some View {
        List(model.symbols, id: \.self) { Text($0) }
            .task { await model.reload() }
            // The indicator stays until reload() returns.
            .refreshable { await model.reload() }
            // Wrong: returns at once, so the indicator hides early.
            // .refreshable { Task { await model.reload() } }
    }
}

go deeper

for a junior

Recall that refreshable adds pull to refresh to a List and that its handler is async, so you await the reload inside it.

for a middle

Explain the RefreshAction environment value, why the indicator tracks the handler's lifetime, and why Task inside the handler breaks it.

for a senior

Show one load path shared by task and refreshable, custom views that read the refresh value, and cancellation kept out of error states.

for a principal

Make shared load and refresh paths the team default, so every list screen has the same loading, error and retry behaviour.

## How the pieces connect Pull to refresh in SwiftUI is built from an **environment value** rather than a property of `List`: - `refreshable(action:)` takes an `async` handler and stores a `RefreshAction` built from it in the view's environment, under the `refresh` key. - By default that environment value is `nil`. Views that find a non-`nil` action can offer a refresh. - On iOS and iPadOS, a `List` that finds one enables the standard pull-to-refresh gesture. - When the person pulls and releases, the list calls the handler and shows a progress indicator. Because it is an environment value, the modifier affects the views beneath the one it is applied to, not only the view it is written on. The same design is what lets a custom view offer refresh at all: anything that can read the environment can discover the action and call it, without knowing who provided it. ## The indicator lasts as long as the action Apple's documentation states that the indicator **remains visible for the duration of the refresh**, which runs asynchronously. The duration is simply the lifetime of your async handler: when it returns, the refresh is over. That makes one rule central: 1. Await the work **inside** the handler: `.refreshable { await model.reload() }`. 2. Do not wrap it in `Task { }`. The handler then returns immediately, the indicator vanishes before any data arrives, and nothing waits on the task you created. 3. With a fire-and-forget task inside, the refresh counts as finished at once, so repeated pulls can start overlapping loads that race to write the same state. The handler inherits the view's actor context, so like the `task` modifier it runs on the main actor, and assigning state after an `await` is safe. ## Common mistakes - **Fire-and-forget inside the handler**, described above. - **Replacing the list with a full-screen spinner** while reloading. The pull indicator belongs to the list; swapping the list out for a `ProgressView` removes the very view showing it and makes the screen jump. - **A separate code path for refresh.** Initial loading and refreshing usually want the same request and error handling; one async method on the model, called from both `task` and `refreshable`, keeps them consistent. - **Reporting cancellation as an error.** If the async work is cancelled, treat that as a normal exit, as with any view-driven task. ## Errors during a refresh A refresh can fail like any load, and the indicator gives no error feedback of its own: it simply disappears when the handler returns. Decide what the person sees: - Keep the previous data on screen and show a short message, rather than clearing the list. - Record when the last successful refresh happened, so the screen can say how fresh the data is. - Catch errors inside the handler or the model method it calls; the handler's type is a non-throwing async closure, so it cannot pass an error back to the list. These choices matter more than the gesture itself, because a pull that silently does nothing teaches people the feature is broken. ## Refreshing custom views Any view can offer refresh by reading the environment value, as Apple's documentation shows: - Declare `@Environment(\.refresh) private var refresh`. - If it is `nil`, hide or disable the refresh control. - If it is present, call it with `await refresh?()`; `RefreshAction` defines `callAsFunction()`, so it is called like a function. - From a button, which is synchronous, wrap the call in a `Task`, and use the call's lifetime to show your own progress indicator. ## refreshable compared with task | Aspect | `task` | `refreshable` | |---|---|---| | Who starts it | SwiftUI, before the view appears | the person, by pulling | | What it adds | an async task | a `RefreshAction` in the environment | | Progress shown | none by itself | the list's indicator, for the handler's duration | | Typical use | first load | reload on demand | Both take async closures and both should call the same model method, so a screen loads the same way whether it is shown for the first time or refreshed by hand. How rows, sections and swipe actions behave inside that list is a separate subject.

  • How do you offer refresh from a custom view instead of a List?
    Read `@Environment(\.refresh)`. When it is `nil`, hide or disable the control; otherwise call it with `await refresh?()`, wrapping the call in a `Task` from a button's synchronous action. Show your own progress while that call is running, since its lifetime is the refresh's lifetime.
  • Should the first load and the refresh call the same code?
    Usually yes: one async method on the model, called from `task` when the screen appears and from `refreshable` when the person pulls. Both paths then share the request, error handling and cancellation rules, and the screen cannot drift into two behaviours. Where that model lives and how it is isolated is an architecture decision.

  • refreshable is a property of List and has no effect on the views beneath it.
  • Wrapping the refresh in Task { } inside the handler is harmless and keeps the spinner up.
  • The refresh indicator stays visible for a fixed time, regardless of the handler.
  • Showing a full-screen ProgressView instead of the list during refresh is the expected pattern.