Who owns a screen's async work: .task, a Task in the model, refreshable and cancellation?
The gist
All async work needs an owner whose lifetime matches how long the work is needed. The owner decides when to cancel it. A SwiftUI screen has three levels of ownership:
.task/.task(id:)— the work belongs to the view's identity: it is cancelled when the view disappears or theidchanges. Loading the screen's data.- A
Taskstored in the model — the work belongs to the screen model: it is cancelled on an event (a new query, a "Stop" button) and tested without UI. - An app-level service — work that must outlive the screen: sending a message, uploading a file, syncing. The screen enqueues the job in the service and observes its status.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep