I've run into an issue with my app that I've been able to narrow down to a small reproducer.
Any time there is a task associated with the DetailView
and you "pop to top", onAppear
is called again and the task is re-run. Why is that? Is this a SwiftUI bug? It doesn't happen on iOS 17, only 18.
import SwiftUI
@Observable
class Store {
var shown: Bool = true
}
@main
struct MyApp: App {
@State private var store = Store()
var body: some Scene {
WindowGroup {
if store.shown {
ContentView()
} else {
EmptyView()
}
}
.environment(store)
}
}
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: DetailView()) {
Text("Go to Detail View")
}
}
}
}
struct DetailView: View {
@Environment(Store.self) private var store
init() {
print("DetailView initialized")
}
var body: some View {
Button("Pop to top") {
store.shown = false
}
.task {
print("DetailView task executed")
}
.onAppear {
print("DetailView appeared")
}
.onDisappear {
print("DetailView disappeared")
}
}
}