History
Loading...
Loading...
September 6, 2025
.task modifier instead of .onAppear for async operations. Unlike onAppear, the task modifier automatically cancels ongoing operations when the view disappears, preventing memory leaks and unwanted network requests.The task modifier provides structured concurrency that automatically handles the async operation lifecycle. When the view appears, the task starts, and crucially, when the view disappears, the task is automatically cancelled.
struct UserProfileView: View {
@State private var user: User?
@State private var isLoading = true
let userID: String
var body: some View {
Group {
if isLoading {
ProgressView("Loading...")
} else if let user = user {
VStack {
Text(user.name)
Text(user.email)
}
} else {
Text("Failed to load user")
}
}
.task {
do {
user = try await UserService.fetchUser(id: userID)
} catch {
print("Error fetching user: \(error)")
}
isLoading = false
}
}
}This prevents common issues like completing network requests for views that are no longer visible, reduces memory usage, and eliminates race conditions where async operations complete after a view has been deallocated. It's cleaner than manually managing Task cancellation and follows Swift's structured concurrency principles.