Async work in SwiftUI: predictable data loading with .task, cancellation, and MainActor
Most SwiftUI screens wait for data from the network or disk at some point. Swift's async/await model made that code readable, but the real difficulty is not the syntax; it is when the work starts and when it ends. What happens to a request that is still running when the user leaves the screen? Does every letter typed quickly into a search field send its own request? Can a late response from an old query overwrite the newer one?
When these questions go unanswered, familiar bugs appear: a closed screen that keeps loading data in the background, search results that briefly belong to the wrong query, UI state modified from off the main thread. In this post I describe the practices I use in SwiftUI to tie async work to the view lifecycle, handle cancellation correctly, and keep state on a single actor.
Tying work to the view lifecycle
Starting a Task { ... } inside onAppear is the first approach that comes to mind, but that task lives independently of the view. When the view goes off screen, the task keeps running and writes its result into state that nobody is looking at anymore.
The .task modifier solves this structurally. The task starts when the view appears and is cancelled automatically when the view is removed:
struct OrderListView: View {
@State private var model: OrderListModel
var body: some View {
List(model.orders) { order in
OrderRow(order: order)
}
.overlay { if model.isLoading { ProgressView() } }
.task { await model.load() }
}
}
The key idea here is that the view owns the task. You don't need to write cancellation code or keep a reference to the task. For the vast majority of loading work that belongs to a screen, this is the right default.
.task(id:) for input-dependent work
Some work should run again not only when the screen opens but also when a value changes: the selected category, the search text, a filter. .task(id:) cancels the previous task and starts a new one every time the given value changes.
.task(id: query) {
do {
try await Task.sleep(for: .milliseconds(300))
await model.search(query)
} catch {
// Cancelled: the user is still typing.
}
}
This small block does two jobs at once. First, debouncing: if the user types another letter within 300 milliseconds, Task.sleep throws a cancellation error and the request is never sent. Second, protection against stale responses: if a new query arrives while the previous search is still waiting on the network, the old task is cancelled. There is no need for a separate timer, a Combine pipeline, or a request counter.
Cancellation is cooperative
In Swift, cancellation does not forcibly stop a task; it only sets a "you have been cancelled" flag. Checking that flag and stopping is the task's own responsibility. Many system calls, such as Task.sleep and the async APIs of URLSession, already respect cancellation and throw an error. In long loops you write yourself, you have to do it:
func importAll(_ items: [RawItem]) async throws -> [Item] {
var result: [Item] = []
for item in items {
try Task.checkCancellation()
result.append(try await transform(item))
}
return result
}
The second critical point is not to show cancellation to the user as an error. Telling a user who left the screen or changed the query that "The request failed" is the wrong message. When catching errors, I handle cancellation separately:
do {
orders = try await api.fetchOrders()
} catch is CancellationError {
return
} catch let error as URLError where error.code == .cancelled {
return
} catch {
errorMessage = "Orders could not be loaded."
}
Because URLSession can throw URLError.cancelled instead of CancellationError when cancelled, both cases need to be checked.
Keeping state on the MainActor
State that the UI reads should change on the main actor. Rather than trying to remember DispatchQueue.main.async on every assignment, it is safer to mark the whole model that holds the state as @MainActor:
@MainActor
@Observable
final class OrderListModel {
private(set) var orders: [Order] = []
private(set) var isLoading = false
var errorMessage: String?
private let api: OrderLoading
init(api: OrderLoading) { self.api = api }
func load() async {
isLoading = true
defer { isLoading = false }
do {
orders = try await api.fetchOrders()
} catch is CancellationError {
return
} catch {
errorMessage = "Orders could not be loaded."
}
}
}
In this setup, the main actor is free while await api.fetchOrders() is in progress, the network work runs elsewhere, and when the result comes back the assignment happens on the main actor again. The compiler catches code that tries to access these properties from outside the main actor. If there is heavy JSON decoding or image processing, it is enough to move that work into a function that is not bound to the main actor, or into a separate actor, and write only the result to the model.
One trap to watch for here is that await points release the actor. State you read before an await may have changed afterwards. For example, if the user deleted an item from the list while loading was in progress, blindly assigning the incoming response can bring that deleted item back. In such cases, you need to re-check the current state before applying the response.
User actions and unstructured tasks
Work that starts when a button is tapped cannot be expressed with .task; using Task { ... } is natural here. This task inherits the context of the actor it was called from, so when started inside a SwiftUI view it runs on the main actor. It is not structured, however: nobody cancels it automatically.
For short operations that should complete, such as saving, this is usually fine. For long-running or repeatable work, you need to keep the task reference and cancel it when necessary:
private var exportTask: Task<Void, Never>?
func startExport() {
exportTask?.cancel()
exportTask = Task { await runExport() }
}
func cancelExport() {
exportTask?.cancel()
}
Task.detached, on the other hand, does not inherit the actor context or priority. In practice it is rarely needed, and it often hides a wrong assumption. To move heavy work away from the main actor, my first choice is not a detached task but a function or service that is not bound to the main actor.
Parallel loading: async let and task groups
If a detail screen needs three independent sources, awaiting them one after another adds unnecessary latency. async let is the most readable way to run a fixed number of tasks in parallel:
func loadDetail(id: Order.ID) async throws {
async let order = api.fetchOrder(id)
async let history = api.fetchHistory(id)
async let notes = api.fetchNotes(id)
detail = try await OrderDetail(order: order, history: history, notes: notes)
}
These child tasks are structured: if the parent task is cancelled, they are all cancelled, and if one throws, the others are cancelled too. When the number of items is only known at runtime, withThrowingTaskGroup provides the same guarantees. Don't forget to put a concurrency limit in place; trying to download hundreds of images at once puts load on both the server and the device.
Testable loaders
The easiest way to test async code is to put the network layer behind a small protocol. The model depends on that protocol instead of a concrete client:
protocol OrderLoading: Sendable {
func fetchOrders() async throws -> [Order]
}
In tests, it is easy to write fake implementations of this protocol that return fixed data, throw an error, or wait until a signal arrives. That way scenarios such as "is isLoading correct during loading", "is the error message set", and "does a cancelled load leave no error message behind" can be verified without opening any UI, without a real network, and without waiting on sleep. Testing the cancellation scenario is especially important, because the bugs that are hardest to catch manually and look strangest to users hide there.
What keeps async code in SwiftUI orderly is not a particular library but a few consistent decisions: work that belongs to a screen is tied to the view with .task, input-dependent work renews itself with .task(id:), cancellation is handled quietly and correctly, and UI state lives on a single actor. When these decisions are made up front, the uncertainty of the network does not disappear, but the screen's behavior becomes predictable and testable.