title: SwiftUI - Update body only once when @EnviromentObject and @State changes
body: <p>I have created this example project replicating my app architecture, in which a random number is generated in a <code>Manager</code> class and then displayed in the <code>SecondaryView</code>. Inside this view, calculations need to be made based on this <code>randomNumber</code> and displayed as well (<code>randomNumberTimesTen</code>). This example is of course non-sensical and could be fixed by changing the architecture. The important part is the relation between <code>@State</code> and <code>@EnvironmentObject</code> and they need to stay where they are.</p>
  <p>How can I make sure that the body of <code>SecondaryView</code> is only updated once after the <code>randomNumberTimesTen</code> has been calculated and not twice? At the moment it happens right away after the <code>randomNumber</code> was generated and this causes issues in my app as I need the value of <code>randomNumberTimesTen</code> before the body can be drawn correctly.</p>
  <p>I think the problematic part might be the <code>.onChange(of: manager.randomNumber)</code> as this is probably only executed when the body is updated. Is there a way to move this somewhere else? The <code>multiplyByTen()</code> needs to stay in the <code>SecondaryView</code> though.</p>
  <p>Example code:</p>
  <pre><code>struct ContentView: View {
      @StateObject var manager = Manager()
      var body: some View {
          VStack {
              SecondaryView()
                  .environmentObject(manager)
              Button(&quot;Random Number&quot;) {
                  manager.generateRandomNumber()
              }
          }
      }
  }
  
  struct SecondaryView: View {
      @State var randomNumberTimesTen: Int = 0
      @EnvironmentObject var manager: Manager
  
      var body: some View {
  
          VStack {
              Text(&quot;Random Number: \(manager.randomNumber)&quot;)
              Text(&quot;Random Number x10: \(randomNumberTimesTen)&quot;)
          }
          .onChange(of: manager.randomNumber) { _ in
              multiplyByTen()
          }
      }
  
      func multiplyByTen() {
          randomNumberTimesTen = manager.randomNumber * 10
      }
  }
  
  
  public class Manager: ObservableObject {
      @Published public var randomNumber: Int = 0
  
      public func generateRandomNumber() {
          self.randomNumber = Int.random(in: 0..&lt;10)
      }
  }
  </code></pre>