0

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).

AlexMath
  • 567
  • 1
  • 6
  • 16
  • This code activates next navigation link *before* previous has finished and this breaks internal states. And, also, be aware that NavigationLink creates destination in place of own creation. – Asperi Nov 25 '20 at 04:44
  • @Asperi When you say the previous navigation link hasn't finished, I'm assuming that's the animation. As far as I know SwiftUI does not allow custom transition animations, which would mean that, to be safe, *all* navigations should check that it has been more than _n_ ms after initialization before transitioning? That doesn't seem desirable. 800 ms seems to do the trick, anyway. – AlexMath Nov 25 '20 at 16:58

0 Answers0