Email copiado — support@tuurt.com
Cargando experiencia
swift · October 31, 2026 · 7 min

Structured Concurrency in Swift: What Happens to Orphaned Tasks When a View Closes

A Task launched from a view that closes before it finishes does not just vanish. We look at why cooperative cancellation matters, and the concrete mistake of storing the Task on a View struct instead of the view model.

By Tuurt Team

Structured Concurrency in Swift: What Happens to Orphaned Tasks When a View Closes

A pattern that shows up in almost any SwiftUI app with remote data: the user opens a detail screen, an async call fires to fetch the content, and before the response arrives, the user navigates back. The view no longer exists. The task we launched to fetch the data, if we did nothing special, keeps running. When it finishes, it tries to update state that no view is observing anymore, and in the best case that is wasted work; in the worst case it is a strong reference to self keeping an instance alive that should have been released, or a crash if the code assumes something still exists.

Swift concurrency does not solve this automatically just because async/await is in use. The structured concurrency model solves it, partially, and only when used correctly.

Structured vs unstructured: the task tree matters

The core idea of structured concurrency in Swift is that a child task lives within the scope of its parent task. If the parent is cancelled, cancellation propagates to its children. This is automatic with async let and with TaskGroup:

func loadFullProfile(id: String) async throws -> FullProfile {
    try await withThrowingTaskGroup(of: Void.self) { group in
        var userData: UserData?
        var orders: [Order] = []

        group.addTask { userData = try await fetchUserData(id) }
        group.addTask { orders = try await fetchOrders(id) }

        do {
            for try await _ in group {}
        } catch {
            group.cancelAll()
            throw error
        }

        guard let userData else { throw ProfileError.incomplete }
        return FullProfile(userData: userData, orders: orders)
    }
}

If one of the two calls fails, we explicitly cancel the rest of the group before rethrowing the error. Without that cancelAll(), the other task keeps running until its own cooperative cancellation checkpoint, spending network and CPU on a result nobody is going to use.

The actual problem is not in TaskGroup, which enforces this model by design. It is in a Task { ... } launched directly, which is unstructured: it has no parent that cancels it automatically when the scope that created it disappears. If a bare Task is launched inside a button action or inside onAppear, that task lives independently of the view's lifecycle, unless something explicitly takes care of cancelling it.

struct OrderDetailView: View {
    let id: String
    @State private var order: Order?

    var body: some View {
        VStack {
            if let order { OrderCard(order: order) }
        }
        .onAppear {
            Task {
                order = try? await fetchOrder(id)
            }
        }
    }
}

This code compiles, works in a demo, and fails silently in production: if the user navigates away before fetchOrder resolves, the Task keeps running, and when it finishes it tries to write order onto a @State that belongs to an instance of OrderDetailView SwiftUI has already discarded. It does not crash -SwiftUI tolerates this without blowing up- but it is a network call that should not have been made, or should have been cancelled as soon as it stopped being needed.

.task solves this, but only if you understand why

SwiftUI exposes the .task modifier precisely for this case: it ties the task's lifecycle to the view's lifecycle, and cancels it automatically when the view disappears.

.task {
    order = try? await fetchOrder(id)
}

The difference from a bare Task { } inside onAppear is not just syntactic. .task is SwiftUI's own responsibility: the framework holds a reference to the Task it creates, and calls .cancel() on it when the view node is removed from the tree. But cancelling is not the same as stopping immediately. Cancellation in Swift concurrency is cooperative: it marks the Task as cancelled and leaves it to the code inside the task to decide what to do with that information at the next checkpoint.

func fetchOrder(_ id: String) async throws -> Order {
    try Task.checkCancellation()
    let data = try await URLSession.shared.data(from: orderURL(id))
    try Task.checkCancellation()
    return try JSONDecoder().decode(Order.self, from: data.0)
}

URLSession's async API respects the cancellation of the Task calling it -if the Task is cancelled while the request is in flight, the underlying HTTP request is cancelled too, not just the result discarded-. That covers the network case. But if there is a heavy computation loop between two await points with no suspension point at all, that code keeps running regardless of the Task already being marked cancelled, because nothing called Task.checkCancellation() or checked Task.isCancelled inside the loop. Cooperative cancellation needs actual cooperation from the code, not just the call to .cancel() at the exit point.

What did not work the first time

The first time we debugged a case like this, the symptom was an intermittent crash when navigating quickly between a list and a detail screen. The code already stored the Task in a property and cancelled it explicitly: loadTask?.cancel() inside onDisappear. It looked correct, and it worked in most cases. The problem only showed up when the view got recreated several times in quick succession during fast navigation, because OrderDetailView is a struct, and SwiftUI can create a new instance of the struct for the same view identity without that reliably and synchronously firing onDisappear on the old instance in step with the expected cancellation. The loadTask property lived on a new instance of the struct, so .cancel() inside onDisappear would sometimes run on a copy that never had the real Task assigned to it, because the assignment had happened on a different instance of the same struct.

The fix was not to chase the struct's lifecycle more carefully, but to move the task out of the view level entirely. We moved the loading logic into an @Observable type that outlives the intermediate structs SwiftUI recreates, and there deinit is a reliable place to cancel, because a class has real identity and a lifecycle that does not get rebuilt on every render:

@Observable
final class OrderDetailViewModel {
    var order: Order?
    private var loadTask: Task<Void, Never>?

    func load(id: String) {
        loadTask = Task {
            order = try? await fetchOrder(id)
        }
    }

    deinit {
        loadTask?.cancel()
    }
}

With the view using .task(id: id) { await viewModel.load(id: id) }, we still get SwiftUI's automatic cancellation for the simple case, and we have an additional, reliable cancellation point in the view model for cases where the task needs to intentionally outlive a one-off struct recreation.

What we check before launching a Task from a view

Before using a bare Task { } in a SwiftUI view, we first check whether .task or .task(id:) covers the case -it almost always does for loading data when a view appears- because that modifier handles cancellation for us with no extra code. If the task needs a lifecycle different from the view's -surviving a navigation, chaining off another user action- we move it into a type with real identity, never into a property of a View struct, because a struct gets recreated and has no deinit to rely on. And in any async function that does more than a single network call, we make sure there is at least one Task.checkCancellation() between expensive operations, because cooperative cancellation only cancels where the code bothers to check.

swift concurrency swiftui ios
← Back to blog