1

I have a banner component written in SwiftUI that I am embedding in a ViewController using a UIHostingController.view as a return type in a method:

public static func createBannerView(thing: String) -> UIView? {
    let viewModel = bannerViewModel(dependency: SomeRepository(thing: thing))
    return UIHostingController(rootView: bannerView(viewModel: viewModel)).view
}

//I do check for nil, but shortened for readability...
infoBanner.addSubview(createBannerView())
    NSLayoutConstraint.activate([...

Inside the view, I am referencing the ViewModel as an @ObservedObject.

I have heard concerns that I should be referencing the ViewModel as a @StateObject instead, because the ViewModel is being created outside of the ViewController. I understand this concern in a situation where the parent view and child view are SwiftUI views, because changes to the immutable parent view will recreate the child view and without the @StateObject declaration the data in the @ObservableObject will be lost.

But in this situation, the parent UIKit powered ViewController is not immutable, and can change all it wants without forcing a redraw of the child SwiftUI view.

My questions:

1: Is there a benefit in this situation to marking the ViewModel as a @StateObject or @ObservedObject

2: Is there a danger to marking the ViewModel as a @StateObject or @ObservedObject

UPDATE

An answer on another thread gives a great explanation of how these two objects differ: @StateObject vs @ObservedObject when passed externally but owned by the view

Wesley
  • 5,381
  • 9
  • 42
  • 65
  • Is there something I can add to my response that would clarify further? – jnpdx Oct 25 '22 at 16:22
  • I was looking for more detail. For example: what is the specific difference in function between the two and what specific dangers will you encounter using them in different scenarios. I found rob mayoffs answer very useful here: https://stackoverflow.com/questions/71060365/stateobject-vs-observedobject-when-passed-externally-but-owned-by-the-view – Wesley Oct 25 '22 at 17:09
  • Okay -- I've removed it as you've found your answer elsewhere. – jnpdx Oct 25 '22 at 17:50
  • Does this answer your question? [@StateObject vs @ObservedObject when passed externally but owned by the view](https://stackoverflow.com/questions/71060365/stateobject-vs-observedobject-when-passed-externally-but-owned-by-the-view) – lorem ipsum Mar 17 '23 at 13:25

0 Answers0