The following works for a wait time of 2 sec, but set it to 0.5 and you can't get past the second screen.
import SwiftUI
let waitTime: TimeInterval = 0.5
class ContentViewModel: ObservableObject {
@Published var shouldNavigate = false
init() {
DispatchQueue.main.asyncAfter(deadline: .now() + waitTime) { [weak self] in
self?.shouldNavigate = true
}
}
}
struct ContentView: View {
@ObservedObject var viewModel = ContentViewModel()
var body: some View {
NavigationView {
VStack{
Text("Hello, world!")
.padding()
NavigationLink(
destination: ContentView2(),
isActive: $viewModel.shouldNavigate,
label: {
EmptyView()
}).isDetailLink(false)
}
}
}
}
struct ContentView2: View {
@ObservedObject var viewModel = ContentViewModel()
var body: some View {
VStack {
Text("View 2")
.padding()
NavigationLink(
destination: ContentView2(),
isActive: $viewModel.shouldNavigate,
label: {
EmptyView()
}).isDetailLink(false)
}
}
}
When I subscribe to shouldNavigate
and print the incoming values, I can see that a short wait time causes it to go to nil
quickly after navigation whereas a longer wait time does not have that effect.
Is there some life-cycle stuff happening that I'm not aware of?
IRL, I show a screen while the view model searches for an advertising BLE peripheral, and navigate when it is discovered. That search can be quite fast. I'd rather not implement some ad-hoc delay since it's smelly (and it feels like I'm lying to the user).