According to Apple's documentation, a task{} will automatically cancel when a view disappears.
SwiftUI will automatically cancel the task at some point after the view disappears before the action completes.
Why, in this scenario, is the Task in the 'loadData' method not cancelled when the ChildView disappears? (When navigating back to the 'ParentView')
struct ChildView: View {
@State private var data: [Double] = []
private func loadData() async {
// Why isn't this Task automatically cancelled when the ChildView disappears?
// The Task is still executing in the background.
Task(priority: .background) {
// Simulating heavy data processing.
self.data = (1...3_000_000).map { _ in Double.random(in: -10...30) }
print("Task ended")
}
}
var body: some View {
Text("This is a child view")
.task { await loadData() }
}
}
struct ParentView: View {
var body: some View {
NavigationStack {
NavigationLink(destination: { ChildView() }) {
Text("Show child view")
}
}
}
}
The task in 'loadData' continues executing even when the ChildView disappears. It also executes multiple times when the ChildView is initialized multiple times in a row.
This could potentially lead to memory leaks, especially when using a class with a @Published 'data' property instead of the @State property in the ChildView. What is the correct implementation for using a Task() in such a scenario?