title: In SwiftUI how can I animate a Published View change?
body: <p>I would like to animate a View change.<br>
  In particular, I have done a View where one of its children is a changing View.</p>
  
  <pre><code>struct MasterView: View {
  
      @State var playerLeft: Bool = false
      @ObservedObject var viewModel: MasterViewModel
  
      var body: some View {
          ZStack {
              WaitPlayerBackView(isShowing: self.$playerLeft) {
                  self.viewModel.currentView
              }
          }
      }
  }
  </code></pre>
  
  <p>The view model is an ObservableObject class. currentView is changed by a method called from an async thread, like this:</p>
  
  <pre><code>class MasterViewModel: ObservableObject {
      @Published var currentView: AnyView = AnyView(EmptyView())
  
      func changeView() {
          self.currentView = AnyView(NightView())
      }
  }
  </code></pre>
  
  <p>It's like a copy of Android fragments (pardon the comparison).<br>
  How can I animate this View change?<br>
  I have tried different options like:</p>
  
  <pre><code>self.viewModel.currentView.animate(.default)
  </code></pre>
  
  <p>or</p>
  
  <pre><code>struct MasterView: View {
  
      @State var playerLeft: Bool = false
      @ObservedObject var viewModel: MasterViewModel
  
      var body: some View {
          ZStack {
              WaitPlayerBackView(isShowing: self.$playerLeft) {
                  self.viewModel.currentView
              }
          }.animate(self.viewModel.animate ? .easeIn(duration: 1) : .none)
      }
  }
  
  class MasterViewModel: ObservableObject {
      @Published var currentView: AnyView = AnyView(EmptyView())
      @Published var animate = false
  
      func changeView() {
          self.animate = false
          self.currentView = AnyView(NightView())
          self.animate = true
      }
  }
  </code></pre>
  
  <p>However, none of them worked.<br>
  This is how I see a transition when changing the instance of currentView.
  <a href="https://i.stack.imgur.com/Aq4uJ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aq4uJ.gif" alt="Example of transitions"></a></p>