title: Keep reference on view/data model after View update
body: <p>Consider we have a <code>RootView</code> and a <code>DetailView</code>. <code>DetailView</code> has it's own BindableObject, let's call it <code>DetailViewModel</code> and we have scenario:</p>
  
  <ol>
  <li><code>RootView</code> may be updated by some kind of global event e.g. missed
      internet connection or by it's own data/view model</li>
  <li>When <code>RootView</code> handling event it's
      content is updated and this is causes new struct of <code>DetailView</code> to
      be created</li>
  <li>If <code>DetailViewModel</code> is created by <code>DetailView</code> on init,
      there would be another reference of <code>DetailViewModel</code> and it's state (e.g. selected object) will be missed</li>
  </ol>
  
  <p>How can we avoid this situation?</p>
  
  <ol>
  <li>Store all ViewModels as EnvironmentObjects that is basically a singleton pool. This approach is causes to store unneeded objects in memory when they are not used</li>
  <li>Pass throw all ViewModels from RootView to it's children and to children of child (has cons as above + painfull dependencies)</li>
  <li>Store View independent DataObjects (aka workers) as EnvironmentObjects. In that case where do we store view dependent states that corresponds to Model? If we store it in View it will end up in situation where we cross-changing @States what is forbidden by SwiftUI</li>
  <li>Better approach?</li>
  </ol>
  
  <p>Sorry me for not providing any code. This question is on architecture concept of Swift UI where we trying to combine <em>declarative structs</em> and <em>reference objects with data</em>. </p>
  
  <p>For now I don't see da way to keep references that corresponds to appropriate view only and don't keep them in memory/environment forever in their current states.</p>
  
  <h2>Update:</h2>
  
  <p>Lets add some code to see whats happening if VM is created by it's View</p>
  
  <pre><code>import SwiftUI
  import Combine
  
  let trigger = Timer.publish(every: 2.0, on: .main, in: .default)
  
  struct ContentView: View {
  
      @State var state: Date = Date()
  
      var body: some View {
          NavigationView {
              VStack {
                  NavigationLink(destination: ContentDetailView(), label: {
                      Text("Navigation push")
                          .padding()
                          .background(Color.orange)
                  })
                  Text("\(state)")
                      .padding()
                      .background(Color.green)
                  ContentDetailView()
              }
          }
          .onAppear {
              _ = trigger.connect()
          }
          .onReceive(trigger) { (date) in
              self.state = date
          }
      }
  }
  
  struct ContentDetailView: View {
  
      @ObservedObject var viewModel = ContentDetailViewModel()
      @State var once = false
  
      var body: some View {
          let vmdesc = "View model uuid:\n\(viewModel.uuid)"
          print("State of once: \(once)")
          print(vmdesc)
          return Text(vmdesc)
              .multilineTextAlignment(.center)
              .padding()
              .background(Color.blue)
              .onAppear {
                  self.once = true
              }
      }
  }
  
  class ContentDetailViewModel: ObservableObject, Identifiable {
      let uuid = UUID()
  }
  </code></pre>
  
  <h2>Update 2:</h2>
  
  <p>It seems that if we store ObservableObject as @State in view (not as ObservedObject) View keeps reference on VM</p>
  
  <pre><code>@State var viewModel = ContentDetailViewModel()
  </code></pre>
  
  <p>Any negative effects? Can we use it like this?</p>
  
  <h2>Update 3:</h2>
  
  <p>It seems that if ViewModel kept in View's @State:</p>
  
  <ol>
  <li>and ViewModel is retained by closure with strong reference - deinit will never be executed -> memory leak</li>
  <li>and ViewModel is retained by closure with weak reference - deinit invokes every time on view update, all <code>subs</code> will be reseted, but properties will be the same</li>
  </ol>
  
  <p>Mehhh...</p>
  
  <h2>Update 4:</h2>
  
  <p>This approach also allows you to keep strong references in bindings closures</p>
  
  <pre><code>import Foundation
  import Combine
  import SwiftUI
  
  /**
   static func instanceInView() -&gt; UIViewController {
       let vm = ContentViewModel()
       let vc = UIHostingController(rootView: ContentView(viewModel: vm))
       vm.bind(uiViewController: vc)
       return vc
   }
   */
  public protocol ViewModelProtocol: class {
      static func instanceInView() -&gt; UIViewController
      var bindings: Set&lt;AnyCancellable&gt; { get set }
      func onAppear()
      func onDisappear()
  }
  
  extension ViewModelProtocol {
  
      func bind(uiViewController: UIViewController) {
          uiViewController.publisher(for: \.parent)
              .sink(receiveValue: { [weak self] (parent) in
                  if parent == nil {
                      self?.bindings.cancel()
                  }
              })
              .store(in: &amp;bindings)
      }
  
  }
  
  struct ModelView&lt;ViewModel: ViewModelProtocol&gt;: UIViewControllerRepresentable {
  
      func makeUIViewController(context: UIViewControllerRepresentableContext&lt;ModelView&gt;) -&gt; UIViewController {
          return ViewModel.instanceInView()
      }
  
      func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext&lt;ModelView&gt;) {
          //
      }
  }
  </code></pre>
  
  <pre><code>struct RootView: View {
  
      var body: some View {
          ModelView&lt;ParkingViewModel&gt;()
              .edgesIgnoringSafeArea(.vertical)
      }
  
  }
  </code></pre>