Find Retained Tasks When A SwiftUI Screen Disappears

The screen disappears, but its model stays alive. The model owns a Task handle, and that task is still waiting for the next event while retaining the model. A deinit that cancels the task never gets a chance to run.

This is an ownership problem before it is a memory-profiler problem. Draw the references, then decide which object owns the operation’s lifetime.

A completed task and an endless task behave differently

Apple’s Task documentation explains that a task releases its closure when it completes. Retaining a completed Task handle does not indefinitely retain everything its closure captured.

An event loop that never completes is different. This shape keeps the receiver alive while consume is suspended:

task = Task { await self.consume(values) }

Dropping the handle also does not cancel the task. It only loses your direct way to await or cancel it. Neither “set task to nil” nor “cancel in deinit” automatically solves the ownership graph above.

Keep the receiver out of the suspension

For a screen-owned stream, capture the stream separately and keep self weak while awaiting the next element. Use the receiver briefly when an element arrives:

import Foundation

@MainActor
final class ScreenWorker {
    private var task: Task<Void, Never>?
    private(set) var latest = 0
    func start(_ values: AsyncStream<Int>) {
        stop()
        task = Task { [weak self] in
            for await value in values {
                guard !Task.isCancelled else { break }
                self?.accept(value)
            }
        }
    }
    private func accept(_ value: Int) { latest = value }
    func stop() {
        task?.cancel()
        task = nil
    }
    deinit { task?.cancel() }
}

The suspended loop holds the stream, but only a weak reference to ScreenWorker. accept is synchronous on the main actor, so it does not extend ownership across another await.

The deinitializer is a cleanup backstop in this version because the task no longer prevents the owner from reaching it. The explicit stop remains useful when the screen stops needing updates before its model is deallocated.

Call stop before replacing the handle. Otherwise, repeated starts can leave several consumers active while you retain only the newest handle.

Be careful where you promote weak self

A weak capture followed immediately by guard let self before an infinite loop holds a strong local reference for that loop’s lifetime. Likewise, calling a long-running async instance method through weak self can retain the receiver for the duration of that call.

The point is not to scatter weak captures everywhere. It is to keep a strong receiver scoped to the work that actually needs it. A short, finite save may reasonably retain its owner until completion. An endless observation owned by a dismissed screen usually should not.

If the work must outlive the screen, give it an owner with that lifetime: an application service, a transfer coordinator, or a persisted job system. Making screen ownership accidentally immortal is not a background-work architecture.

Cancellation still needs cooperation

Apple documents Task.cancel() as cooperative. Cancelling arbitrary synchronous work does not interrupt it at the next instruction.

This example uses AsyncStream, whose waiting iterator responds to task cancellation. A custom AsyncSequence or callback adapter needs its own cancellation behavior, including releasing observers or closing the underlying resource where appropriate.

The loop checks cancellation before applying a delivered element. That protects this local UI update boundary; it does not undo work the producer already performed.

Verify the reference graph directly

The companion creates a deliberately strongly captured worker, drops its external owner, and confirms a weak reference remains non-nil. It then cancels and awaits the task, after which the weak reference becomes nil.

The corrected worker is released when its external owner is dropped. The fixture uses stream lifetime control, not a guessed sleep to “let ARC catch up.”

In the app, repeat the actual navigation path several times and inspect surviving instances in the memory graph. Also check external subscriptions: a Combine sink, notification observer, or delegate can retain the same model independently of its task.

September 2026 review: the ownership assertions passed with Swift 6.4, and the example type-checked for iOS 17. The fixture tests reference lifetime; it does not claim a measured memory reduction in a production screen.