title: Where do I handle the initial value before the first onChange(of:)?
body: <p>I want to load some data when my app is first launched, and when the app is <strong>foregrounded</strong> I want to ensure I have the latest data.</p>
  <p>The state is stored in a ViewModel class, which my view owns as a <code>@StateObject</code>. I read the <code>ScenePhase</code> from the Environment, and in <code>onChange(of: scenePhase)</code>, I call a method on my ViewModel to start the reload if needed.</p>
  <p>But when should I start the <em>initial</em> load?</p>
  <ul>
  <li><code>ContentView.init</code> is too early, because <code>scenePhase</code> is <code>.background</code>. And even if it were <code>.active</code>, I'm apparently not supposed to access StateObject from init — SwiftUI logs a runtime warning.</li>
  <li><code>ViewModel.init</code> is too early as well — theoretically, I think the view model could be created even if the app were never brought to the foreground.</li>
  <li>The first time <code>var body</code> is accessed, the scenePhase is <code>.active</code>. <code>onChange(of:)</code> doesn't call the closure for its initial value, so it's never called until I background and re-foreground the app.</li>
  </ul>
  <pre><code>class ViewModel: ObservableObject {
    init() {
      // 1. reload() here? Could happen without the app entering the foreground.
    }
  
    func reload() { ... }
  }
  
  
  struct ContentView: View {
    @Environment(\.scenePhase) var scenePhase
    @StateObject var viewModel = ViewModel()
  
    init() {
      // 2. viewModel.reload() here?
      //  - problem 1: scenePhase == .background, not .active
      //  - problem 2: not supposed to access a @StateObject here anyway
    }
  
    var body: some View {
      (...)
        // The initial render happens when scenePhase == .active,
        // so I don't get the onChange callback until it changes again.
        .onChange(of: scenePhase) {
          if $0 == .active {
            viewModel.reload()
          }
        }
    }
  }
  </code></pre>